-2

当运行代码在控制台中给出这个错误。我使用 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;
    }
4

1 回答 1

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()方法在后台线程完成执行后被调用。您可以UIThreadonPostExecute(). 因此,只需在后台线程中编写您的网络代码,然后您就可以在onPostExecute().

希望这可以帮助。谢谢。

于 2012-10-16T08:44:34.507 回答