当前位置: 首页 > 知识库问答 >
问题:

Android操作系统。android 4.2的NetworkOnMainThreadException[重复]

柴辰阳
2023-03-14

在这里,我正在使用此代码加载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。

共有3个答案

洪开济
2023-03-14

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

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

看到这个了吗

禄烨然
2023-03-14

这是正确的方法:

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

称它(从main):

mJSONParser = new JSONParser();
mJSONParser.execute();
白修谨
2023-03-14

在setContentView(R.layout.activity_main)之后,将下面的代码写入MainActive文件;

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;
 类似资料:
  • 在我的应用程序中,我得到了android。操作系统。NetworkOnMainThreadException。我正在尝试从url获取图像,当时我遇到了这个异常。若我在2.2中运行应用程序,它可以正常工作,但若我在4.0中运行,就会出现异常。 我有错误 在这一行请帮我解决这个问题 我使用了AsyncTask 我在这行中遇到了错误: Logcat:

  • 其中“url”是JSON格式的,它使用http GET方法返回大量数据。 我无法从我在getResultForRequest(url)方法中传递的“url”中获取JSON格式的数据。我在urlConnection.connect();中出错。Internet权限也在AndroidManifest.xml文件中给出。 这是我的日志。 提前谢谢。

  • 我在运行RssReader的Android项目时出错。 代码: 它显示了以下错误: 如何解决此问题?

  • 操作系统提供的服务 操作系统的五大功能,分别为:作业管理、文件管理、存储管理、输入输出设备管理、进程及处理机管理 中断 所谓的中断就是在计算机执行程序的过程中,由于出现了某些特殊事情,使得CPU暂停对程序的执行,转而去执行处理这一事件的程序。等这些特殊事情处理完之后再回去执行之前的程序。中断一般分为三类: 内部异常中断:由计算机硬件异常或故障引起的中断; 软中断:由程序中执行了引起中断的指令而造成

  • sed sed是非交互式的编辑器。它不会修改文件,除非使用shell重定向来保存结果。默认情况下,所有的输出行都被打印到屏幕上。sed编辑器逐行处理文件(或输入),并将结果发送到屏幕。 sed命令行格式为: sed [-nefri] ‘command’ 输入文本 常用选项: -n∶使用安静(silent)模式。在一般 sed 的用法中,所有来自 STDIN的

  • 问题内容: 我已经做了一些研究,但这个问题已经提出,但不是我打算的那样。我正在为QR登陆的客户端构建页面,这是一个下载应用程序的地方。因此,他不必在页面上打印2个QR码,我想检测当前的操作系统(Apple / Android / Other [不支持])并根据该值修改我的元素。 我已经看过脚本“ detectmobilebrowsers”,它的目的只是告诉用户是否完全可以移动,而我想弄清楚用户正在