使用HTTPURLConnection在Java中进行HTTP到HTTPS重定向

时间:2016-04-29 05:13:42

标签: java httpurlconnection url-redirection

我在java代码中连接到特定网址的HTTP请求时遇到问题。例如: http://www.linkedin.com 。这会引发服务器不可用错误。 (TimeOutException)。 但是,如果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();
  }

1 个答案:

答案 0 :(得分:1)

您的代码适合我。显然,您正面临一些网络问题。

http://www.linkedin.com是否在您的浏览器中运行? 如果是,那么您可以检查它是否使用了某些代理。