26

在这里,我正在使用此代码加载 Json。它适用于 android 2.2,但是当我使用 android 4.2 时,它会抛出android.os.NetworkOnMainThreadException 异常,请给我解决方案

 public class JSONParser {

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

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

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        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;

}

}

我也在使用谷歌 api。

4

5 回答 5

81

在 setContentView(R.layout.activity_main); 之后将以下代码写入您的 MainActivity 文件中;

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

并将下面的 import 语句放入您的 java 文件中。

import android.os.StrictMode;
于 2013-05-08T11:38:34.413 回答
13

这是正确的方法:

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

    static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

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


    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(url);

            HttpResponse getResponse = httpClient.execute(httpPost);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();

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

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IO", e.getMessage().toString());
        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;


}
protected void onPostExecute(String page)
{   
    //onPostExecute
}   
}

调用它(从主):

mJSONParser = new JSONParser();
mJSONParser.execute();
于 2013-05-08T11:56:33.220 回答
6

请确保您不在 UI 线程上进行任何网络访问,而是在 异步任务中进行

您的应用程序在 Android 3.0 及更高版本上崩溃但在 Android 2.x 上运行良好的原因是因为 HoneyComb 对 UI 线程的滥用更加严格。例如,当运行 HoneyComb 或以上版本的 Android 设备检测到 UI 线程上有网络访问时,会抛出 NetworkOnMainThreadException。

看到这个

于 2013-05-08T11:36:48.363 回答
1

android.os.NetworkOnMainThreadException当您尝试在主线程上访问网络时发生(您的主要活动执行)。为避免这种情况,您必须创建一个单独的线程AsyncTaskRunnable实现来执行 JSON 数据加载。由于 HoneyComb,您无法在主线程上进一步执行网络任务。 AsyncTask用于网络任务执行的实现

于 2013-05-08T11:37:19.827 回答
1

使用 StrictMode 像这样的东西:-

   if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 
        }
于 2013-05-08T11:39:02.543 回答