Search code examples
apache-httpclient-5.x

How to acquire the response body from Apache HttpClient5's HttpResponse?


Getting the status code and response body was this easy in version 4:

StringEntity entity = new StringEntity(jsonData.toString());
HttpResponse r = org.apache.http.client.fluent.Request.Post(uri)
        .connectTimeout(10*1000)
        .socketTimeout(10*1000)
        .addHeader("Content-Type", "application/json; charset=utf-8")
        .body(entity)
        .execute()
        .returnResponse();
int status = r.getStatusLine().getStatusCode();
String body = EntityUtils.toString(r.getEntity(), "UTF-8");
return new CoolResponse(status, body);

But now in httpclient5 for some reason it isn't possible to get anything relating to the response body from an HttpResponse. Very confused by this. If I follow example 3 in their quickstart (https://hc.apache.org/httpcomponents-client-5.0.x/quickstart.html) it proposes I create an CloseableHttpClient, an HttpGet and a CloseableHttpResponse, but none of those allow you to set a connection timeout. Trying to find the best of both worlds but the options seem kind of scrambled here.


Solution

  • It's not mentioned in the quickstart, but in the fluent API you can follow up execute() with handleResponse() and pass it a lambda.

    I wound up finding a much better article than the quickstart here: https://ok2c.github.io/httpclient-migration-guide/migration-to-classic.html

    Edit: that link is down, there is now an equivalent guide on apache's site https://hc.apache.org/httpcomponents-client-5.2.x/migration-guide/migration-to-classic.html