我不明白为什么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();
}
}
}
该程序的输出为:
原始网址:http://httpstat.us/301 连接到:http://httpstat.us/301 收到的HTTP响应代码:301 收到HTTP响应消息:永久移动
对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 将按照预期进行重定向!