2013-10-17 91 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; 

} 

我GOOGLE了很多從url獲取json字符串,但我認爲是時候問我這個問題了。幾乎所有這個問題的算法都不適合我。它確實需要與AsyncTask一起使用嗎?我在Android的初學者,所以我不知道很多。請幫幫我。或者,如果您可以提供更好的算法,請這樣做。總是意外停止

+2

你可以發佈堆棧跟蹤嗎? – Raghunandan

+0

你面臨什麼錯誤?沒有錯誤=沒有幫助。 – GrIsHu

+1

你是否以json的形式從服務器獲得任何響應? –

回答

0

使用BufferedReader中的物體,像這樣讀

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); 

是必須,當你調用一個使用異步任務Web服務,因爲Http調用不會在主線程上進行,您應該使用另一個線程來調用長時間運行的操作。在異步任務

更多信息在developers website

0

是的,你是正確的給出。您應該使用異步任務從服務器獲取數據 -

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) { 
    } 
} 

現在將其調用onCreate方法。

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; 
    }