ThisCalculator

Everyday

HTTP Status Code with Apache HttpClient

Updated · Standard formula, shown below

This guide shows you how to retrieve the HTTP status code from a response using Apache HttpClient, the popular Java library for making HTTP requests. You’ll learn the exact steps to execute a request, capture the response, and read the status code, along with common pitfalls and troubleshooting tips. By the end, you’ll be able to handle response codes confidently in your Java applications.

What You’ll Need

  • Java Development Kit (JDK) 8 or later installed on your machine.
  • Apache HttpClient library (version 4.5.x or 5.x) added to your project. For Maven, add the dependency org.apache.httpcomponents:httpclient:4.5.14 (or httpclient5:5.2.1 for the newer API). For Gradle, use implementation 'org.apache.httpcomponents:httpclient:4.5.14'.
  • An IDE or text editor to write and run Java code.
  • Basic familiarity with Java syntax and exception handling.

Step-by-Step

  1. Create an HttpClient instance. In HttpClient 4.x, use CloseableHttpClient httpClient = HttpClients.createDefault();. In 5.x, use CloseableHttpClient httpClient = HttpClients.createDefault(); (same method name).
  2. Build an HTTP request. For a GET request, use HttpGet request = new HttpGet("https://api.example.com/data");. For POST, use HttpPost and set the entity if needed.
  3. Execute the request. Call CloseableHttpResponse response = httpClient.execute(request);. This sends the request and blocks until a response is received.
  4. Extract the status code. Use int statusCode = response.getStatusLine().getStatusCode();. In HttpClient 5.x, the method is response.getCode() (since getStatusLine() is deprecated).
  5. Use the status code. For example, check if it’s 200 (OK) or 404 (Not Found) and handle accordingly. You can also log it or use it in conditional logic.
  6. Close the response. Always close the response in a finally block or use try-with-resources to release the connection. Example: try (CloseableHttpResponse response = httpClient.execute(request)) { ... }.
  7. Close the client. When done, close the httpClient to free resources: httpClient.close(); (or use try-with-resources).

Common Mistakes

  • Forgetting to close the response or client. This leads to connection leaks and resource exhaustion. Always close in finally or use try-with-resources.
  • Using the wrong method in HttpClient 5.x. In 5.x, getStatusLine() is deprecated; use response.getCode() instead.
  • Not handling exceptions. Network issues, timeouts, and malformed URLs throw IOException and URISyntaxException. Wrap your code in try-catch blocks.
  • Assuming the response body is always present. For status codes like 204 No Content or 304 Not Modified, there is no body. Reading it will throw an error.
  • Ignoring redirects. By default, HttpClient follows redirects, so the final status code may be 200 even if the original request returned 302. If you need the original, disable redirects.

Tips

  • Use try-with-resources for both the response and the client to ensure automatic cleanup.
  • Set reasonable timeouts (e.g., RequestConfig with connection and socket timeouts) to avoid hanging requests.
  • For status codes that indicate errors (4xx, 5xx), log the response body if available, as it often contains error details.
  • If you need to handle multiple requests, reuse the same HttpClient instance – it’s thread-safe and designed for that.
  • Consider using a helper method to centralize status code retrieval and error handling.

Troubleshooting

Problem: The status code is always 200, even when the server should return an error. This often happens because the server returns a 200 with an error message in the body (e.g., JSON with "error": true). Check the response body for error indicators. Alternatively, the client may be following redirects – disable redirects to see the intermediate code.

Problem: org.apache.http.client.ClientProtocolException or HttpHostConnectException. This usually means the URL is malformed, the host is unreachable, or the server is down. Verify the URL, check your internet connection, and ensure the server is running.

Problem: NoHttpResponseException – the server closed the connection without a response. This can happen if the server times out or if the request is malformed. Retry with a fresh connection or increase the socket timeout.

Problem: The code compiles but throws NullPointerException on getStatusLine(). Ensure the response is not null – this can happen if the execute method returns null (rare). Also, in HttpClient 5.x, use getCode() instead.

Problem: SSLHandshakeException when using HTTPS. This indicates a certificate issue. If it’s a test environment, you may need to configure a trust manager, but for production, ensure the certificate is valid.

Frequently Asked Questions

How do I get the status code in Apache HttpClient 5?

Use response.getCode() instead of getStatusLine().getStatusCode(). The rest of the flow is the same.

Can I get the status code without reading the response body?

Yes, the status code is available immediately after executing the request, before reading the body. You can close the response without consuming the entity, but be aware that the connection may not be reusable.

What is the difference between getStatusLine() and getCode()?

getStatusLine() returns a StatusLine object that contains the protocol version, status code, and reason phrase. getCode() (in 5.x) directly returns the integer status code. Both are equivalent in information.

How do I handle redirects to get the original status code?

Disable automatic redirects by setting RequestConfig.custom().setRedirectsEnabled(false).build() and attach it to the request or client. Then you’ll get the 3xx status code.

Is it safe to reuse the HttpClient instance for multiple requests?

Yes, CloseableHttpClient is thread-safe and designed for reuse. Create one instance and share it across your application.

What should I do if the status code is 500 (Internal Server Error)?

Log the status code and the response body (if any) for debugging. The server-side logs will help identify the cause. You might also retry the request after a delay if the error is transient.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.