2013-10-17 3 views
-1
public JSONObject getJSONFromUrl(String url) { 
    InputStream is = null; 
    JSONObject jObj = null; 
    String json = ""; 

    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 

URL에서 json 문자열을 많이 봤지만 인터넷에이 질문을 할 때가되었습니다. 이 문제의 거의 모든 알고리즘이 나를 위해 작동하지 않습니다. AsyncTask와 함께 사용해야합니까? 나는 안드로이드에서 초보자이므로 많이 알지 못합니다. 도와주세요. 또는 더 나은 알고리즘을 제공 할 수 있다면 그렇게하십시오. 이 방법처럼의 BufferedReader 객체를 사용하여 읽기예기치 않게 항상 중단되었습니다.

+2

스택 추적을 게시 할 수 있습니까? – Raghunandan

+0

어떤 오류가 있습니까? 오류 없음 = 도움말이 없습니다. – GrIsHu

+1

json의 형태로 서버에서 응답을 받고 있습니까? –

답변

0

try { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
     sb.append(line); // Don't use \n this will make your json object invalid 
    } 
    is.close(); 
    json = sb.toString(); 
} catch (Exception e) { 
    Log.e("Buffer Error", "Error converting result " + e.toString()); 
} 

0

그것은이 AsyncTask를 할 필요가 없습니다 시도하지만 (여기서 UI 메인 스레드보다 다른 뭔가를 않습니다 실행). 예를 들어 AsyncTask 대신 쓰레드.

그렇지 않으면 4.0 이후의 Android 버전에서 'NetworkOnMainThread'예외가 발생합니다. 자세한 내용은 Netwok on main thread exception in android 4.0을 참조하십시오.

0

난 당신이 호출하여 응답 서버를 요청하는 생각 HttpPost 당신이 당신이 이 방법이 뭔가를 얻을 수 HttpGet라고해야 대신 서버에 무언가를 게시하지 않는 한 잘못입니다 방법

 DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     httpGet.setHeader("Accept", "application/json"); 
     httpGet.setHeader("Content-Type", "application/json"); 
     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     String ss = EntityUtils.toString(httpEntity); 
     System.out.println("response" + ss); 
같은 서버

당신이 호출 할 때 예 비동기 작업을 사용해야합니다 웹 서비스는 Http 호출이 메인 스레드에서 이루어지지 않기 때문에 오랫동안 실행중인 작업을 호출하기 위해 다른 스레드를 사용해야합니다. 비동기 작업에

더 많은 정보는

0

네, 맞아요 developers website에 제시되어있다. 서버에서 데이터를 가져 오는 데 비동기 작업을 사용해야합니다.

public class getData extends AsyncTask<String, Void, String> { 

    ProgressDialog pd = null; 

    @Override 
    protected void onPreExecute() { 
     pd = ProgressDialog.show(LoginPage.this, "Please wait", 
       "Loading please wait..", true); 
     pd.setCancelable(true); 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 

      HttpClient client = new DefaultHttpClient(); 

      HttpGet request = new HttpGet(Constant.URL + "/register.php?name=" 
        + userName + "&email=" + userName + "&gcm_regid=" 
        + Registration_id); 

      HttpResponse response = client.execute(request); 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent())); 
      System.out.println("***response****" + response); 
      String webServiceInfo = ""; 
      while ((webServiceInfo = rd.readLine()) != null) { 
       jsonObj = new JSONObject(webServiceInfo); 
       Log.d("****jsonObj", jsonObj.toString()); 

       break; 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 

     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
    } 
} 

이제는이 메서드를 호출하여 메서드를 호출하십시오.

new getData().excute(); 

고마워요!

0

logcat을 게시하지 않으므로 문제를 추측하기가 어렵습니다. 하지만 여기서는 응용 프로그램 중 하나에서 사용한 JSON 응답을 얻기위한 코드를 제공하고 있으며 원활하게 작동합니다. 나는 그것이 당신을 위해서도 잘되기를 바랍니다.

public static String parseJSON(String p_url) { 
     JSONObject jsonObject = null; 
     String json = null; 
     try { 
      // Create a new HTTP Client 
      DefaultHttpClient defaultClient = new DefaultHttpClient(); 
      // Setup the get request 
      HttpGet httpGetRequest = new HttpGet(PeakAboo.BaseUrl + p_url); 
      System.out.println("Request URL--->" + PeakAboo.BaseUrl + p_url); 
      // Execute the request in the client 
      HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 
      // Grab the response 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpResponse.getEntity().getContent(), "UTF-8")); 
      json = reader.readLine(); 
      System.err.println("JSON Response--->" + json); 
      // Instantiate a JSON object from the request response 
      jsonObject = new JSONObject(json); 

     } catch (Exception e) { 
      // In your production code handle any errors and catch the 
      // individual exceptions 
      e.printStackTrace(); 
     } 
     return jsonObject; 
    } 
관련 문제