简体   繁体   中英

Not getting the right header response code with HttpUrlConnection

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM