问题描述:

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.

相关阅读:
Top