使用 HTTPURLConnection 在 java 中将 HTTP 重定向到 HTTPS
HTTP to HTTPS Redirection in java using HTTPURLConnection
我在连接到 java 代码中特定 url 的 HTTP 请求时遇到问题。例如:http://www.linkedin.com。这会引发服务器不可用错误。 (超时异常)。
但是,我希望我的连接将 http 请求重定向到 Location header Value if responseCode 是 301 或 302。
代码片段:
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();
}
你的代码对我有用。显然,您遇到了一些网络问题。
http://www.linkedin.com 在您的浏览器中工作吗?
如果是,那么你可以检查它是否使用了一些代理。
我在连接到 java 代码中特定 url 的 HTTP 请求时遇到问题。例如:http://www.linkedin.com。这会引发服务器不可用错误。 (超时异常)。 但是,我希望我的连接将 http 请求重定向到 Location header Value if responseCode 是 301 或 302。
代码片段:
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();
}
你的代码对我有用。显然,您遇到了一些网络问题。
http://www.linkedin.com 在您的浏览器中工作吗? 如果是,那么你可以检查它是否使用了一些代理。