【发布时间】:2016-08-24 03:01:13
【问题描述】:
在我的 java 代码中连接到特定 url 的 HTTP 请求时遇到问题。例如:http://www.linkedin.com。这会引发服务器不可用错误。 (超时异常)。 但是,如果 responseCode 为 301 或 302,我希望我的连接将 http 请求重定向到 Location 标头值。
代码片段:
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 代码进行自动重定向。在尝试建立连接时检查您的网络
netstat -na并查找 SYN_SENT 状态 -
如果您在网络上实现了代理,请尝试使用 SSL 上下文实现它,如this 帖子中所述。
标签: java httpurlconnection url-redirection