【问题标题】:HTTP to HTTPS Redirection in java using HTTPURLConnection使用 HTTPURLConnection 在 java 中的 HTTP 到 HTTPS 重定向
【发布时间】: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


【解决方案1】:

您的代码对我有用。显然,您正面临一些网络问题。

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

【讨论】:

    猜你喜欢
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 2011-09-06
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多