我在我的Java代码中连接到一个特定URL的HTTP请求时遇到了问题。例如:http://www.linkedin.com。这会抛出“服务器不可用”错误(TimeOutException)。
但是,如果响应代码为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();
}
netstat -na
并查找SYN_SENT状态。 - Jan