Java - 如何查找网址的重定向网址? [英] Java - How to find the redirected url of a url?
问题描述
我通过java访问网页如下:
I am accessing web pages through java as follows:
URLConnection con = url.openConnection();
但在某些情况下,网址会重定向到另一个网址。所以我想知道上一个网址重定向的网址。
But in some cases, a url redirects to another url. So I want to know the url to which the previous url redirected.
以下是我收到的标题字段:
Below are the header fields that I got as a response:
null-->[HTTP/1.1 200 OK]
Cache-control-->[public,max-age=3600]
last-modified-->[Sat, 17 Apr 2010 13:45:35 GMT]
Transfer-Encoding-->[chunked]
Date-->[Sat, 17 Apr 2010 13:45:35 GMT]
Vary-->[Accept-Encoding]
Expires-->[Sat, 17 Apr 2010 14:45:35 GMT]
Set-Cookie-->[cl_def_hp=copenhagen; domain=.craigslist.org; path=/; expires=Sun, 17 Apr 2011 13:45:35 GMT, cl_def_lang=en; domain=.craigslist.org; path=/; expires=Sun, 17 Apr 2011 13:45:35 GMT]
Connection-->[close]
Content-Type-->[text/html; charset=iso-8859-1;]
Server-->[Apache]
所以目前,我正在从 Set-Cookie
标题字段的值构建重定向的url。在上面的例子中,重定向的网址是 copenhagen.craigslist.org
So at present, I am constructing the redirected url from the value of the Set-Cookie
header field. In the above case, the redirected url is copenhagen.craigslist.org
我有什么标准方式可以通过可以确定特定网址要重定向的网址。
Is there any standard way through which I can determine which url the particular url is going to redirect.
我知道当网址重定向到其他网址时,服务器会发送包含<$ c $的中间响应c>位置标题字段,告诉重定向的URL,但我没有通过 url.openConnection();
方法接收该中间响应。
I know that when a url redirects to other url, the server sends an intermediate response containing a Location
header field that tells the redirected url but I am not receiving that intermediate response through the url.openConnection();
method.
推荐答案
您需要将 URLConnection
转换为 HttpURLConnection
并通过设置不关注重定向/net/HttpURLConnection.html#setInstanceFollowRedirects%28boolean%29\"rel =noreferrer> HttpURLConnection#setInstanceFollowRedirects()
到 false
。您也可以通过全局设置它 HttpURLConnection#setFollowRedirects()
。
You need to cast the URLConnection
to HttpURLConnection
and instruct it to not follow the redirects by setting HttpURLConnection#setInstanceFollowRedirects()
to false
. You can also set it globally by HttpURLConnection#setFollowRedirects()
.
您只需要自己处理重定向。通过 <$查看回复代码c $ c> HttpURLConnection#getResponseCode() ,通过位置标题。 sun.com/javase/6/docs/api/java/net/URLConnection.html#getHeaderField%28java.lang.String%29rel =noreferrer> URLConnection#getHeaderField()
然后在其上发出新的HTTP请求。
You only need to handle redirects yourself then. Check the response code by HttpURLConnection#getResponseCode()
, grab the Location
header by URLConnection#getHeaderField()
and then fire a new HTTP request on it.
这篇关于Java - 如何查找网址的重定向网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!