2012-11-20 51 views
0

我從我的Android設備連接到Webservice,然後發送參數並獲取json。 它確定當我測試與Android API < 4.0 ex 2.3.3 當我測試與另一個設備,它的API是4.0.3,4.0.4 然後我無法接收JSON。僅接收json時出錯Android 4.0

這是我的代碼

json = getJson("http://search.twitter.com/search.json?result_type=recent&rpp=3&q=iphone"); 


private String getJson(String uri) { 

    String json = null; 
    try { 
     URL url = new URL(uri); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("Accept", "application/json"); 
     Log.d(TAG,"1"); 
     // conn.setConnectTimeout(10 * 1000); //6s 
     if (conn.getResponseCode() == 200) { 
      // get successfull 
      // read Json 
      Log.d(TAG,"2"); 
      BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); 
      int len = 0; 
      byte[] buf = new byte[1024]; 
      StringBuffer stringBuffer = new StringBuffer(); 
      while ((len = in.read(buf)) != -1) { 
       String s = new String(buf, 0, len); 
       stringBuffer.append(s); 
      } 
      Log.d(TAG,"3"); 

      json = stringBuffer.toString(); 
      Log.d(TAG,json); 
     } 
    } catch (Exception e) { 
     Log.e(TAG, "error get json :" + e.toString()); 
     json = null; 
    } 
    return json; 
} 

錯誤。

11-20 19:42:22.555: E/TEST(29097): error get json :android.os.NetworkOnMainThreadException 

回答

4

它適用於您的2.3.3因爲自從API 11 你需要移動使用的HTTP連接到另一個線程,或更好地利用AsyncTask的部分NetworkOnMainThreadException已經在Android的..

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { 
protected Long doInBackground(URL... urls) { 
    int count = urls.length; 
    long totalSize = 0; 
    for (int i = 0; i < count; i++) { 
     totalSize += Downloader.downloadFile(urls[i]); 
     publishProgress((int) ((i/(float) count) * 100)); 
     // Escape early if cancel() is called 
     if (isCancelled()) break; 
    } 
    return totalSize; 
} 

protected void onProgressUpdate(Integer... progress) { 
    setProgressPercent(progress[0]); 
} 

protected void onPostExecute(Long result) { 
    showDialog("Downloaded " + result + " bytes"); 
} 
} 
0

呼叫從的AsyncTask < web服務>。問題將解決。