我不能理解为什么 Java 的 HttpURLConnection
不遵循从 HTTP 到 HTTPS URL 的 HTTP 重定向。我使用以下代码获取 https://httpstat.us/的页面:
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStream;
public class Tester {
public static void main(String argv[]) throws Exception{
InputStream is = null;
try {
String httpUrl = "http://httpstat.us/301";
URL resourceUrl = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection)resourceUrl.openConnection();
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.connect();
is = conn.getInputStream();
System.out.println("Original URL: "+httpUrl);
System.out.println("Connected to: "+conn.getURL());
System.out.println("HTTP response code received: "+conn.getResponseCode());
System.out.println("HTTP response message received: "+conn.getResponseMessage());
} finally {
if (is != null) is.close();
}
}
}
这个程序的输出是:
Original URL: http://httpstat.us/301 Connected to: http://httpstat.us/301 HTTP response code received: 301 HTTP response message received: Moved Permanently
对 http://httpstat.us/301的请求返回以下(缩短后的)响应(这似乎是绝对正确的!) :
HTTP/1.1 301 Moved Permanently
Cache-Control: private
Content-Length: 21
Content-Type: text/plain; charset=utf-8
Location: https://httpstat.us
不幸的是,Java 的 HttpURLConnection
不遵循重定向!
注意,如果您将原始 URL 更改为 HTTPS (https://httpstat.us/301) ,Java威尔将按照预期的方式执行重定向! ?