Search code examples
androidandroid-asynctasknetworkonmainthread

BufferedReader with InputStreamReader fed with a finished HTTPResponse causes NetworkOnMainThreadException


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.


Solution

  • 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.