我有一个简单的情况。
给定一个 URL,服务器 header 响应代码将为 HTTP 200。
现在我尝试使用另一个 URL,其中服务器首先响应 HTTP 302(已找到),然后重定向并响应 header HTTP 200 代码。
因此,在第二种情况下,为什么 connection.getResponseCode()
不返回 HTTP 302 而是直接返回 HTTP 200。我实际上有兴趣检查初始响应中的 header 响应HTTP 302 响应。
这是简化的 HttpUrlConnection 代码(几乎是许多开源实现的副本)。
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;
}
额外信息:HTTP 302 包含 header 键:'location',但正如预期的那样,connection.getheaderFields()
不包含它。
最佳答案
您可以配置是否自动跟随重定向;见http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#setFollowRedirects%28boolean%29 .
关于java - 使用 HttpUrlConnection 未获得正确的 header 响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27742460/