[java] How to get HttpClient returning status code and response body?

I am trying to get Apache HttpClient to fire an HTTP request, and then display the HTTP response code (200, 404, 500, etc.) as well as the HTTP response body (text string). It is important to note that I am using v4.2.2 because most HttpClient examples out there are from v.3.x.x and the API changed greatly from version 3 to version 4.

Unfortunately I've only been able to get HttpClient returning the status code or the response body (but not both).

Here's what I have:

// Getting the status code.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
HttpResponse resp = client.execute(httpGet);

int statusCode = resp.getStatusLine().getStatusCode();


// Getting the response body.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
ResponseHandler<String> handler = new BasicResponseHandler();

String body = client.execute(httpGet, handler);

So I ask: Using the v4.2.2 library, how can I obtain both status code and response body from the same client.execute(...) call? Thanks in advance!

This question is related to java http apache-httpclient-4.x http-status-code-415

The answer is


Fluent facade API:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // ??????????(???????)
    String responseContent = EntityUtils.toString(
            httpResponse.getEntity(), StandardCharsets.UTF_8.name());
}

You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.


If you are using Spring

return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to apache-httpclient-4.x

HttpClient won't import in Android Studio JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10) How to set TLS version on apache HttpClient Java HttpRequest JSON & Response Handling What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API? Write in body request with HttpClient fix java.net.SocketTimeoutException: Read timed out Deprecated Java HttpClient - How hard can it be? How to get HttpClient returning status code and response body? How to add,set and get Header in request of HttpClient?

Examples related to http-status-code-415

How can I get the status code from an http error in Axios? Curl to return http status code along with the response Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details How to deal with http status codes other than 200 in Angular 2 HTTP 415 unsupported media type error when calling Web API 2 endpoint AngularJS POST Fails: Response for preflight has invalid HTTP status code 404 Laravel - Return json along with http status code Swift Alamofire: How to get the HTTP response status code Spring Boot Rest Controller how to return different HTTP status codes? Http 415 Unsupported Media type error with JSON