0

我从我的 Android 设备连接到 Webservice,然后发送参数并获取 json。当我用 android API < 4.0 ex 2.3.3 测试时没问题当我用另一台设备测试时,它的 api 是 4.0.3, 4.0.4 然后我无法接收 json。

这是我的代码

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 回答 2

4

它适用于您的2.3.3,因为NetworkOnMainThreadException自api 11以来一直在 android 中 您需要将使用HTTP连接的部分移动到另一个线程,或者更好地使用AsyncTask ..

 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");
 }
}
于 2012-11-20T12:54:32.093 回答
0

从 Asynctask<> 调用 web 服务。问题会解决的。

于 2012-11-20T13:23:52.000 回答