为什么Java的HttpsURLConnection和curl的HEAD请求会返回不同的标头?

时间:2016-11-30 21:47:07

标签: java curl https http-headers httpsurlconnection

当我使用HEAD请求时,我注意到javax.net.ssl.HttpsURLConnection错过了响应中的某些标头。

以下是我使用的代码:

  public static void getHeaders() throws IOException, URISyntaxException {
        URL url = new URL("https://acme-v01.api.letsencrypt.org/terms");
        HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
        con.setRequestMethod("HEAD");
        con.getInputStream().close();
        System.out.println(con.getHeaderField("Location"));
        Map<String, List<String>> map = con.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey() +
                    " ,Value : " + entry.getValue());
        }
    }

输出是下一个:

null
Key : X-Frame-Options ,Value : [DENY]
Key : null ,Value : [HTTP/1.1 200 OK]
Key : Cache-Control ,Value : [max-age=60987]
Key : Server ,Value : [nginx]
Key : ETag ,Value : ["582cdb9c-22004"]
Key : Connection ,Value : [keep-alive]
Key : Expires ,Value : [Thu, 01 Dec 2016 14:26:25 GMT]
Key : Last-Modified ,Value : [Wed, 16 Nov 2016 22:20:12 GMT]
Key : Date ,Value : [Wed, 30 Nov 2016 21:29:58 GMT]
Key : Content-Type ,Value : [application/pdf]

我们可以看到它没有返回“位置”标题。

这是在同一台服务器上执行的简单curl请求:

# curl -I https://acme-v01.api.letsencrypt.org/terms
HTTP/1.1 302 Moved Temporarily
Server: nginx
Content-Type: text/plain; charset=utf-8
Boulder-Request-Id: JBtoTNb6Q-vvdR5VF9j3gIP27S4RmEqaLjepyF60aVU
Location: https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf
Replay-Nonce: x7jscxXZ-90jzgLG8vkmunp7XrlLrMT0R4mzFV7xAhQ
X-Frame-Options: DENY
Strict-Transport-Security: max-age=604800
Content-Length: 0
Expires: Wed, 30 Nov 2016 21:37:03 GMT
Cache-Control: max-age=0, no-cache, no-store
Pragma: no-cache
Date: Wed, 30 Nov 2016 21:37:03 GMT
Connection: keep-alive

为什么相等的“HEAD”请求会返回不同的标头?

1 个答案:

答案 0 :(得分:1)

正如zapl在评论中所说,这是因为此链接具有重定向。而且似乎默认情况下HttpsURLConnection接受重定向。但我们可以手动将其关闭:

con.setInstanceFollowRedirects(false);