loopj/android-async-http — Issue #37: NPE in HttpClient on http status 204
Author: RomainSaury
Created: 2012-02-10 15:02:00+00:00
State: open

Hi,

While using your lib i got a "NPE in HttpClient" error logged in Loggcat on a request that was always ending in a failure.
As the same request was working perfectly fine when i was testing it myself i took a look on your code and found the following code in AsyncHttpRequest :

try {
makeRequest();
return;
} catch (IOException e) {
cause = e;
retry = retryHandler.retryRequest(cause, ++executionCount, context);
} catch (NullPointerException e) {
// there's a bug in HttpClient 4.0.x that on some occasions causes
// DefaultRequestExecutor to throw an NPE, see
// http://code.google.com/p/android/issues/detail?id=5255
Log.e("AsyncHttpRequest", "NPE in HttpClient", e);
cause = new IOException("NPE in HttpClient" + e.getMessage());
retry = retryHandler.retryRequest(cause, ++executionCount, context);
}

As i wasn't using any proxy, i continued deeper in the code and found that theHttpResponseInterceptor sets to the httpClient in the AsyncHttpClient constructor wasn't testing null HttpEntity (which can actually happens when no response is sent | http status 204).

I would suggest to add an early return when the entity is null which wouldn't raise any NPE.

httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
final HttpEntity entity = response.getEntity();
// Here entity is null if the http status of the request was 204, no response
// if (entity == null) {
// return;
// }
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});