2012-11-20 3 views
0

Android 기기에서 Webservice로 연결 한 다음 매개 변수를 전송하고 json을 가져옵니다. 안드로이드 API로 테스트 할 때 괜찮습니다. < 4.0 예 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

IT는 NetworkOnMainThreadExceptionAPI를 당신은 다른 스레드에 HTTP 연결, 또는 더 나은 사용 AsyncTask을 사용하는 부분을 이동해야하는 11 부터 안드로이드되었습니다 당신의 2.3.3 때문에 작동 ..

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 <에서 webservice를 호출하십시오. 문제가 해결 될 것입니다.

관련 문제