HTTPURLConnection不跟隨從HTTP重定向到HTTPS - HTTPURLConnection Doesn't Follow Redirect from HTTP to HTTPS

問題:

I can't understand why Java's HttpURLConnection does not follow an HTTP redirect from an HTTP to an HTTPS URL. 我不明白爲什麼Java的HttpURLConnection不遵循從HTTP到HTTPS URL的HTTP重定向。 I use the following code to get the page at https://httpstat.us/ : 我使用以下代碼在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();
        }
    }
}

The output of this program is: 該程序的輸出爲:

Original URL: http://httpstat.us/301
Connected to: http://httpstat.us/301
HTTP response code received: 301
HTTP response message received: Moved Permanently

A request to http://httpstat.us/301 returns the following (shortened) response (which seems absolutely right!): 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

Unfortunately, Java's HttpURLConnection does not follow the redirect! 不幸的是,Java的HttpURLConnection沒有遵循重定向!

Note that if you change the original URL to HTTPS ( https://httpstat.us/301 ), Java will follow the redirect as expected!? 請注意,如果將原始URL更改爲HTTPS( https://httpstat.us/301 ),Java 按照預期進行重定向!


解決方案:

參考: https://stackoom.com/en/question/7uAo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章