【问题标题】:Get the redirected URL of a very specific URL (in Java)获取一个非常具体的 URL 的重定向 URL(在 Java 中)
【发布时间】:2014-01-14 01:04:52
【问题描述】:

如何获取http://at.atwola.com/?adlink/5113/1649059/0/2018/AdId=4041444;BnId=872;itime=15692006;impref=13880156912668385284的重定向URL;在 Java 中?

我的代码(如下所示)是根据堆栈溢出(尤其是https://stackoverflow.com/a/5270162/1382251)上类似问题的答案构建的。

但它只生成原始 URL。我怀疑还有其他类似的情况,所以我想具体解决这个问题并使用通用解决方案。

    String ref = "http://at.atwola.com/?adlink/5113/1649059/0/2018/AdId=4041444;BnId=872;itime=15692006;impref=13880156912668385284;";
    try
    {
        URLConnection con1 = new URL(ref).openConnection();
        con1.connect();
        InputStream is = con1.getInputStream();
        URL url = con1.getURL();
        is.close();
        String finalPage = url.toString();
        if (finalPage.equals(ref))
        {
            HttpURLConnection con2 = (HttpURLConnection)con1;
            con2.setInstanceFollowRedirects(false);
            con2.connect();
            if (con2.getResponseCode()/100 == 3)
                finalPage = con2.getHeaderField("Location");
        }
        System.out.println(finalPage);
    }
    catch (Exception error)
    {
        System.out.println("error");
    }

【问题讨论】:

    标签: java http-redirect url-redirection


    【解决方案1】:

    我使用 telnet、wget 和 curl 对您的 URL 进行了一些操作,我注意到在某些情况下服务器返回响应 200 OK,有时返回 302 Moved Temporarily。主要区别似乎是请求 User-agent 标头。如果您在con1.connect() 之前添加以下内容,您的代码将有效:

    con1.setRequestProperty("User-Agent","");
    

    也就是说,对于空的 User-Agent(或者如果标头根本不存在),服务器会发出重定向。使用 Java 用户代理(在我的情况下为 User-Agent: Java/1.7.0_45)和默认的 curl 用户代理(User-Agent: curl/7.32.0),服务器响应 200 OK。

    在某些情况下,您可能还需要设置:

    System.setProperty("http.agent", "");
    

    Setting user agent of a java URLConnection

    运行该站点的服务器是 Adtech Adserver,显然它正在执行user agent sniffing。有一个long history of user agent sniffing。因此,似乎最安全的做法是将用户代理设置为 Mozilla:

    con1.setRequestProperty("User-Agent","Mozilla"); //works with your code for your URL
    

    也许最安全的选择是使用一些流行的网络浏览器使用的用户代理。

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 2013-02-03
    • 2012-05-21
    • 2014-01-02
    • 2013-06-29
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多