http连接android.os.NetworkOnMainThreadException ..是什么原因

时间:2012-10-16 07:51:53

标签: android json getjson

当运行代码在控制台中出现此错误时。我使用Web服务从服务器的json api获取数据。

是什么原因?

10-16 13:17:33.389: E/log_tag(651): Error in http connection android.os.NetworkOnMainThreadException
10-16 13:17:33.389: E/log_tag(651): Error converting result java.lang.NullPointerException
10-16 13:17:33.399: E/log_tag(651): Error parsing data org.json.JSONException: End of input at character 0 of 

运行此类时出错

public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static JSONObject getJSONfromURL(String url) {

        // initialize
        InputStream is = null;
        String result = "";
        String error_text="";
        JSONObject j = null;

        // http post
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            HttpParams myParams = null;
            HttpConnectionParams.setConnectionTimeout(myParams, 10000);
            HttpConnectionParams.setSoTimeout(myParams, 10000);

            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        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();
            result = sb.toString();
            //System.out.println("Result = " + result);

        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            //jArray = new JSONObject(result);
            response_status = j.getString("response_status").toString().trim();

            if (response_status.equals("0")) {
                String getcustomer_id = j.getString("customer_id").toString().trim();
                String getPassword = j.getString("password").toString()
                        .trim();
                passData(getcustomer_id, getPassword);
            } else {
                String getcustomer_id = j.getString("response_status").toString()
                        .trim();
                String getPassword = j.getString("error_text").toString()
                        .trim();
                passData(getcustomer_id, getPassword);
            }

        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return j;
    }

    private static void passData(String getcustomer_id, String getPassword) {
        id = getcustomer_id;
        password = getPassword;
    }

1 个答案:

答案 0 :(得分:3)

当应用程序尝试在其主线程上执行网络操作时,抛出此异常。在AsyncTask中运行代码:

class GetJSONFromUrl extends AsyncTask<String, Void, RSSFeed> {

    InputStream is = null;
    String result = "";
    String error_text="";
    JSONObject j = null;

    protected void doInBackground(String... urls) {

    // http post
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(urls[0]);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        HttpParams myParams = null;
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);

        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }
    }

    protected void onPostExecute(String result) {
        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();
        result = sb.toString();
        //System.out.println("Result = " + result);

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        //jArray = new JSONObject(result);
        response_status = j.getString("response_status").toString().trim();

        if (response_status.equals("0")) {
            String getcustomer_id = j.getString("customer_id").toString().trim();
            String getPassword = j.getString("password").toString()
                    .trim();
            passData(getcustomer_id, getPassword);
        } else {
            String getcustomer_id = j.getString("response_status").toString()
                    .trim();
            String getPassword = j.getString("error_text").toString()
                    .trim();
            passData(getcustomer_id, getPassword);
        }

    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
        super.onPostExecute(result)
    }
}

您可以使用new GetJSONFromUrl().execute(url);从代码中的任意位置调用此方法。

网络任务需要在DoInBackground线程中完成,因为在HoneyComb上面的版本中,您无法在UIThread上执行网络任务。这里,在后台线程完成执行后调用onPostExecute()方法。您可以从UIThread访问onPostExecute()。因此,只需在后台线程中编写网络代码,然后就可以在onPostExecute()中的主线程上执行任务。

希望这会有所帮助。感谢。