ScreenshotNeo

BlogHow-to

How to Get the HTTP Response Status Code with Apache HttpClient

Read an HTTP response status code with Apache HttpClient 5.x or 4.x, handle the response body, and avoid common resource-lifecycle mistakes.

By the ScreenshotNeo team4 October 20266 min read

Direct answer: With Apache HttpClient 5.x, read response.getCode(). With HttpClient 4.x, use response.getStatusLine().getStatusCode(). The method changed between major versions, so check your dependency and imports before choosing a snippet.

1. Choose the method for your HttpClient version

Version Status code
HttpClient 5.x response.getCode()
HttpClient 4.x response.getStatusLine().getStatusCode()

Apache’s migration guide maps the 4.x status-line expression to the 5.x response-code method. HttpClient 5 response messages no longer expose a status line. See the Apache migration guide and the HttpClient 5 response API.

2. HttpClient 5.x: read the code in a response handler

The response-handler form is a compact way to inspect the response while the client manages the response lifecycle. This example prints the status and consumes the entity so the connection can be released safely.

import org.apache.hc.client5.http.classic.methods.ClassicRequestBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class StatusCode5 {
    public static void main(String[] args) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            var request = ClassicRequestBuilder.get("https://example.com").build();
            Integer statusCode = client.execute(request, response -> {
                int code = response.getCode();
                System.out.println("HTTP status: " + code);
                EntityUtils.consume(response.getEntity());
                return code;
            });
            System.out.println("Returned status: " + statusCode);
        }
    }
}

The status is an integer. A successful HTTP exchange can still produce a non-success status such as a redirect, client error, or server error; decide what those codes mean for your application rather than assuming execution itself throws for every non-2xx response.

HttpClient 5.x with a returned response

If you use an execution overload that returns a response, close it explicitly. Consume or otherwise handle the entity before expecting the underlying connection to be reusable.

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;

public class StatusCode5Response {
    public static void main(String[] args) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://example.com");
            try (CloseableHttpResponse response = client.execute(request)) {
                int statusCode = response.getCode();
                System.out.println(statusCode);
                EntityUtils.consume(response.getEntity());
            }
        }
    }
}

Apache’s HttpClient quick start demonstrates reading getCode(), consuming entities, and closing returned responses.

3. HttpClient 4.x: read the status line

For an existing 4.x dependency, get the status from the response’s status line and close both the response and client.

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class StatusCode4 {
    public static void main(String[] args) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://example.com");
            try (CloseableHttpResponse response = client.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println(statusCode);
                EntityUtils.consume(response.getEntity());
            }
        }
    }
}

This follows the Apache HttpClient 4.5 tutorial. The imports are different from 5.x, so avoid mixing the two APIs in one snippet or source file.

4. Interpret the result and handle the body

  1. Execute the request. A status code is available on the response created by execution, not on the request object.
  2. Read the code while the response is in scope. In a handler, inspect the response argument. With a returned response, keep access inside its try-with-resources block.
  3. Handle the entity. Read the body if needed, or consume it when you do not need it. Leaving a streamed body unconsumed can prevent safe connection reuse or cause the connection to be discarded.
  4. Close resources. Use try-with-resources for the client and any returned closeable response.
  5. Apply your own status policy. Branch on the integer code where the application needs different handling for success, redirects, or errors.

Do not treat a status code as proof that the response body has a particular format. Check headers and handle empty or unexpected bodies as appropriate for your application.

5. Version and migration considerations

First inspect your build file and imports to determine whether the project uses HttpClient 4.x or 5.x. The migration changes more than this one call; do not swap only the method while leaving old imports in place. Apache describes HttpClient 4.5.x as receiving fixes for major defects and security issues and encourages 4.x users to migrate, but an application should use the API matching its actual dependency until the migration is planned. See the Apache project status.

6. Troubleshooting

Symptom Likely cause Fix
getCode() cannot be resolved The project uses HttpClient 4.x, or imports are from the 4.x package. Use getStatusLine().getStatusCode() for 4.x, or complete a deliberate migration to 5.x and update dependencies and imports.
getStatusLine() cannot be resolved The response type is from HttpClient 5.x. Use getCode() with the 5.x response API.
Response body reads fail after checking status The code consumed the entity before the body was read, or the response was closed too early. Read the body first, then consume or close resources after processing.
Connections are not reused as expected A response entity was left unread or unconsumed. Consume the entity or read it fully, and close returned responses.
The printed code is an error or redirect The remote server returned that status; obtaining a response does not itself mean the request succeeded. Inspect the code and response headers/body, then implement the application’s retry, redirect, or error policy.

7. Performance, reliability, and cost notes

  • Performance: Reading the status integer is inexpensive. Body handling and connection reuse have more practical impact; consume or process the entity and close resources promptly.
  • Reliability: Keep the response within its resource scope and account for non-success statuses explicitly. Network failures may prevent a response from being available at all.
  • Cost: Apache HttpClient is a Java HTTP client library; this API call itself does not establish a per-request service price. Any network, hosting, or upstream costs depend on your environment and destination.

8. Or skip the browser setup

For website screenshots, ScreenshotNeo is a screenshot API and MCP server. It is a separate option from Apache HttpClient: use it when the job is capturing a rendered page as an image or PDF rather than making a Java HTTP request.

One GET request returns a screenshot. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and billing status.
  • An MCP server lets AI agents using Claude, Cursor, or another MCP client take screenshots, inspect page information, and capture PDFs.
  • 1,000 screenshots per month are free with no card. Paid plans start at $5 for 3,000; every feature is on every plan.

Sign up for ScreenshotNeo and get 1,000 free screenshots a month with no card.

9. FAQ

Does the status code method return an integer?

Yes. Both version-specific calls provide the HTTP status code as an integer.

Can I get the status code from the request?

No. Execute the request and read the code from the resulting response.

Should I migrate from HttpClient 4.x just to change this method?

The method difference alone does not require an immediate migration. Match the code to the dependency you have, and evaluate migration using Apache’s project guidance and your application’s compatibility needs.