4

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();
  }
Bhim singh dangi
  • 417
  • 1
  • 5
  • 12
  • A timeout exception does not indicate a failed redirect - more likely you hit a firewall. HttpUrlConnection does automatic redirect nased on 30x codes. Check your network `netstat -na` while connection is trying to establish and look for SYN_SENT status – Jan Apr 29 '16 at 05:51
  • 1
    If you have a proxy implemented on your network, try implementing this with SSL Context as described in [this](http://stackoverflow.com/questions/1511674/how-do-a-send-an-https-request-through-a-proxy-in-java) post. – redoc Apr 29 '16 at 06:52

1 Answers1

1

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.

yurko
  • 1,502
  • 1
  • 13
  • 14