简体   繁体   中英

Can EntityUtils.toString() cause a NetworkOnMainThreadException?

I have a setup where I perform my http requests in the doInBackground() method of an AsyncTask as follows:

@Override
protected HttpResponse doInBackground(HttpRequestBase... httpRequests)
{
    HttpResponse httpResponse = HttpClient.execute(HttpUriRequest);
    return httpResponse;
}

This HttpResponse object is then passed on to the onPostExecute() method of my AsyncTask to be passed on to a handler (the original caller of the http request) and processed as necessary, as follows:

  • checking the response code using httpResponse.getStatusLine().getStatusCode() ;
  • getting the response content using EntityUtils.toString(httpResponse.getEntity()) ).

This setup has been working fine on phones running older versions of Android.

Running my app now on Ice Cream Sandwich (Galaxy Nexus) I find that the first few http requests in my app as above work fine but then there is this one http request which consistently throws an exception with a stack trace as follows (trimmed slightly for readability):

....

at org.apache.http.util.EntityUtils.toString(EntityUtils.java:139)

at java.io.InputStreamReader.close(InputStreamReader.java:145)

at org.apache.http.conn.EofSensorInputStream.close(EofSensorInputStream.java:213)

...

at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:151)

at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)

android.os.NetworkOnMainThreadException

I am confused. Does this then mean that the EntityUtils.toString(HttpEntity) method is a potential culprit for throwing the new (and ever so annoying) NetworkOnMainThreadException ? If so, any advice on reworking my setup to make http requests in a separate thread such that the response can be processed on the main thread?

Please try the following: modify your doInBackground function to return the value of the HTTP response.

protected String doInBackground(HttpRequestBase... httpRequests)
{
    HttpResponse httpResponse = HttpClient.execute(HttpUriRequest);
    if (httpResponse.getEntity() != null) {
      return EntityUtils.toString(httpResponse.getEntity());
    }
    return "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM