使用 HttpUrlConnection 未获得正确的 header 响应代码

Not getting the right header response code with HttpUrlConnection

我的情况很简单。

给定一个 URL,服务器 header 响应代码将为 HTTP 200。

现在我正在用另一个 URL 尝试它,其中服务器首先响应 HTTP 302(找到),然后重定向并响应 header HTTP 200 代码。

因此,在第二种情况下,为什么 connection.getResponseCode() 不 return HTTP 302 而是直接 returns HTTP 200。我实际上有兴趣检查header 初始 HTTP 302 响应中的响应

这是简化的 HttpUrlConnection 代码(几乎是许多 open-source 实现的副本)。

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