1

I have a simple situation.

Given one URL, the server header response code will be HTTP 200.

Now I'm trying it with another URL where the server FIRST responded with HTTP 302 (Found) and THEN redirects and responded with the header HTTP 200 code.

Hence, in second case, why connection.getResponseCode() does not return HTTP 302 and instead directly returns HTTP 200. I'm actually interested in checking the header response within the initial HTTP 302 response.

Here's the simplified HttpUrlConnection code (almost a carbon copy of many open-source implementations).

private int responseCode;
private Map<String, List<String>> headerFields;

public String getString(String url)
{
    String response = null;
    try
    {
        URL mUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
        connection.setRequestMethod("GET");

        responseCode = connection.getResponseCode();
        headerFields = connection.getHeaderFields();         

        /* boilerplate buffered reader stuffs for getting stream + StringBuilder etc etc.*/

    }
    finally
    {
        connection.disconnect();
    }
    return response;
}

Extra info: The HTTP 302 contains the header key: 'location', though as expected, connection.getheaderFields() does not contain it.

1 Answer 1

3

You can configure whether redirects are automatically followed; see http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#setFollowRedirects%28boolean%29.

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

1 Comment

I see. Though in this case, setInstanceFollowRedirects would be the correct manner to handle this. Setting this however give me a different response code though, which is HTTP 301 (moved permanently). However it did gave me the header key I'm looking for. Regardless, thanks.

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.