3
我在連接到我的Java代碼中特定URL的HTTP請求時遇到問題。例如:http://www.linkedin.com。這會引發服務器不可用錯誤。 (TimeOutException)。 不過,我想我的連接重定向HTTP請求到Location頭值如果responseCode是301或302使用HTTPURLConnection在HTTP中對HTTP進行HTTPS重定向
代碼段:
HttpURLConnection urlConn =(HttpURLConnection) new URL(url).openConnection(); //For eg : http://www.linkedin.com
urlConn.setConnectTimeout(10*1000);
urlConn.setReadTimeout(10*1000);
boolean redirect = false;
int status = urlConn.getResponseCode(); //No response. Throws exception
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM)
{
redirect = true;
}
String contenttype = urlConn.getContentType();
if(redirect)
{
String newUrl = urlConn.getHeaderField("Location");//No I18N
urlConn = (HttpURLConnection) new URL(newUrl).openConnection();
urlConn.connect();
contenttype = urlConn.getContentType();
}
超時異常並不表示失敗的重定向 - 更可能是您碰到了防火牆。 HttpUrlConnection自動重定向30x代碼。在連接嘗試建立並查找SYN_SENT狀態時,請檢查您的網絡'netstat -na' – Jan
如果您的網絡上已實施代理,請嘗試使用SSL上下文執行此操作,如[this]中所述(http://stackoverflow.com/questions/1511674/how-do-a-send-an-https-request-through-a-proxy-in-java)post。 – redoc