Java - 如何查找网址的重定向网址?

时间:2010-04-17 15:56:27

标签: java url http-headers

我通过java访问网页如下:

URLConnection con = url.openConnection();

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

以下是我收到的标题字段:

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标题字段的值构建重定向的网址。在上述情况下,重定向的网址为copenhagen.craigslist.org

我是否有任何标准方法可以确定特定网址将重定向的网址。

我知道当网址重定向到其他网址时,服务器会发送一个包含Location标头字段的中间响应,该字段会告知重定向的网址,但我没有通过url.openConnection();方法收到该中间响应。

6 个答案:

答案 0 :(得分:86)

在调用getInputStream()之后,只需在URLConnection实例上调用getUrl():

URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();

如果您需要知道重定向是否在实际获取内容之前发生,以下是示例代码:

HttpURLConnection con = (HttpURLConnection)(new URL( url ).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
int responseCode = con.getResponseCode();
System.out.println( responseCode );
String location = con.getHeaderField( "Location" );
System.out.println( location );

答案 1 :(得分:52)

您需要将URLConnection转换为HttpURLConnection,并通过将HttpURLConnection#setInstanceFollowRedirects()设置为false来指示关注重定向。您也可以通过HttpURLConnection#setFollowRedirects()全局设置它。

您只需要自己处理重定向。按HttpURLConnection#getResponseCode()检查响应代码,按URLConnection#getHeaderField()抓取Location标题,然后在其上发出新的HTTP请求。

答案 2 :(得分:8)

public static URL getFinalURL(URL url) {
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
        con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
        con.addRequestProperty("Referer", "https://www.google.com/");
        con.connect();
        //con.getInputStream();
        int resCode = con.getResponseCode();
        if (resCode == HttpURLConnection.HTTP_SEE_OTHER
                || resCode == HttpURLConnection.HTTP_MOVED_PERM
                || resCode == HttpURLConnection.HTTP_MOVED_TEMP) {
            String Location = con.getHeaderField("Location");
            if (Location.startsWith("/")) {
                Location = url.getProtocol() + "://" + url.getHost() + Location;
            }
            return getFinalURL(new URL(Location));
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    return url;
}

获取" 用户代理"和" Referer "您可以自己进入已安装浏览器的开发者模式(例如,在Google Chrome上按F12)。然后转到标签'网络'然后单击其中一个请求。你应该看到它的细节。只需按下标题'子选项卡(下图) request details

答案 3 :(得分:1)

查看HttpURLConnection班级API documentation,尤其是setInstanceFollowRedirects()

答案 4 :(得分:0)

我实际上建议使用一个可靠的开源库作为http客户端。如果您通过ASF查看http client,您会发现生活更轻松。它是一个易于使用,可扩展且强大的http客户端。

答案 5 :(得分:-3)

@balusC我写的那样做了。就我而言,我已经添加了cookie信息以便能够重用会话。

Option Explicit
Sub work()
Dim i As Integer
Dim main As Worksheet
Dim reference As Worksheet

Set main = ActiveSheet
Workbooks.Open "C:\Users\vqm1628\Downloads\b.csv"
Set reference = ActiveSheet
Range(Cells(1, 1), Cells(Cells(1, 1).End(xlDown).Row, 1)).Copy _
    Destination:=main.Cells(1, main.Cells(1, 100).End(xlToLeft).Column + 1)
'the line above only applies if the first five columns have values
Application.DisplayAlerts = False
Workbooks("b.csv").Close
Application.DisplayAlerts = True
End Sub