Saya tidak mengerti mengapa Java HttpURLConnection
tidak mengikuti pengalihan HTTP dari HTTP ke URL HTTPS. Saya menggunakan kode berikut untuk mendapatkan halaman di 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();
}
}
}
Output dari program ini adalah:
URL Asli: http://httpstat.us/301 Terhubung ke: http://httpstat.us/301 Kode tanggapan HTTP diterima: 301 Pesan tanggapan HTTP diterima: Dipindahkan Secara Permanen
Permintaan ke http://httpstat.us/301 mengembalikan respons (dipersingkat) berikut (yang tampaknya benar!):
HTTP/1.1 301 Moved Permanently
Cache-Control: private
Content-Length: 21
Content-Type: text/plain; charset=utf-8
Location: https://httpstat.us
Sayangnya, Java HttpURLConnection
tidak mengikuti pengalihan!
Perhatikan bahwa jika Anda mengubah URL asli ke HTTPS ( https://httpstat.us/301 ), Java akan mengikuti pengalihan seperti yang diharapkan !?