Java - 如何找到网址的重定向网址? [英] Java - How to find the redirected url of a url?

查看:25
本文介绍了Java - 如何找到网址的重定向网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过java访问网页如下:

I am accessing web pages through java as follows:

URLConnection con = url.openConnection();

但在某些情况下,一个网址会重定向到另一个网址.所以我想知道上一个url重定向到的url.

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.在上面的例子中,重定向的 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.

我知道当一个 url 重定向到其他 url 时,服务器会发送一个中间响应,其中包含一个 Location 标头字段,该字段告诉重定向的 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 并指示它不要 通过设置 <代码>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().

那时您只需要自己处理重定向.通过 HttpURLConnection#getResponseCode(),通过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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆