2

Does the Apache HttpClient handle GET requests differently compared to java.net.HttpURLConnection?

I tried making a GET request to a URL which returns a redirect using both methods. While the response code from HttpURLConnection returns a 302 as expected, making the same call using HttpClient results in a 200.

Below is my code:

// Using Apache HttpClient
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpGet request = new HttpGet(authUrl);
HttpResponse response = client.execute(request);
int responseCode = response.getStatusLine().getStatusCode();  //Returns 200

// Using java.net.HttpURLConnection
URL obj = new URL(authUrl);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
int responseCode = conn.getResponseCode();  //Returns 302

This is my first time using Apache HttpClient, so my code might be wrong.

Thanks.

2
  • Look at the headers for "Location" - you can get the redirect from that. for (Header header : response.getHeaders("Location")) { redirectLink = header.getValue(); } Commented Mar 14, 2016 at 4:01
  • I've tried that. It doesn't have any "Location" header because the response is 200, and not a 302. Commented Mar 14, 2016 at 4:26

2 Answers 2

1

Handling GET requests - Apache HttpClient vs java.net.HttpURLConnection If you need to walk through a chain of redirects, you should set redirects disabled for HttpPost/HttpGet (HttpRequestBase), for example:

public void disableRedirect(HttpRequestBase request) {
    request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
}

After that you will get expected 302 response code with response.getStatusLine().getStatusCode() and may read headers as @Ascalonian said

Sign up to request clarification or add additional context in comments.

Comments

0

Try turning off automatic redirect handling. Most likely HttpClient redirects to a location specified in 302 response, while HUC for some reason does not

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.