I am facing an Issue while connecting to an HTTP request for a particular url in my java Code. For eg: http://www.linkedin.com . This throws Server Not available Error. (TimeOutException) . But, I want my connection to redirect http request to Location header Value if responseCode is 301 or 302.
Code Snippet:
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();
}
Your code works for me. Obviously, you are facing some network issues.
Is http://www.linkedin.com working in your browser? If yes , then you can check whether it's using some proxy.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.