BufferedReader with InputStreamReader fed with a finished HTTPResponse causes NetworkOnMainThreadException

StackOverflow https://stackoverflow.com/questions/23291471

I have some code that converts my HTTPResponse Object into a JSONObject, which works fine most of the time:

public static JSONObject httpResponseToJson(HttpResponse response) {
    if (response != null) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
                    "UTF-8"));
            String json = reader.readLine();
            if (json != null) {
                JSONObject jsonObject = new JSONObject(json);
                printStatus(jsonObject);
                return jsonObject;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

However, sometimes it throws a the Android NetworkOnMainThread exception. I cannot figure out why, because the response is already finished and there should not be any more network IO involved in that call. For test reasons, if I allow NetworkOnMainThread, this method works fine all the time.

Note that all the HTTPResponse is fetched with an AsyncTask and this is working fine.

I am very interested in any suggestions.

有帮助吗?

解决方案

Reading the response from a HttpResponse object also involves a Network Operation. Simply process that also in the doInBackground() method and modify your AsyncTask to pass to the onPostExecute() the real result once processed.

其他提示

its mean you are performing some network operation on main thread.The point here is Unless the stream is not closed, you are still performing network operation so move that part into doInBackGround() too.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top