【问题标题】:Retrieve the redirected URL of a specific URL, with Java / HttpURLConnection使用 Java / HttpURLConnection 检索特定 URL 的重定向 URL
【发布时间】:2014-01-16 02:18:52
【问题描述】:

我如何获得以下 URL 的“最终位置”(又名登录页面):

http://pixel.mathtag.com/click/img?mt_aid=3432042357544051869&mt_id=540771&mt_adid=100306&mt_sid=293670&mt_uuid=52bf1f56-6fe2-5261-010a-0bbc2fa71e3e&mt_3pck=http%3A//track.pubmatic.com/AdServer/AdDisplayTrackerServlet%3FclickData%3DJnB1YklkPTIwOTc3JnNpdGVJZD0zMDE1MSZhZElkPTI2NjA0JmthZHNpemVpZD05JnRsZElkPTAmcGFzc2JhY2s9MCZjYW1wYWlnbklkPTEyMTYmY3JlYXRpdmVJZD0wJmFkU2VydmVySWQ9MjQz_url%3D&redirect=http://weeklyad.target.com

我的代码(如下)将此字符串作为输入。

输出应该是类似“http://weeklyad.target.com”的东西,但我得到的只是相同的 URL。

不用说,我无法解决这个具体的案例,但我仍然需要一个通用的解决方案。

这是我的简单 Java 代码,使用 HttpURLConnection(其中 String ref 是输入):

        HttpURLConnection con = (HttpURLConnection)new URL(ref).openConnection();
        con.setInstanceFollowRedirects(true);
        con.setRequestProperty("User-Agent","");
        if (con.getResponseCode()/100 == 3)
        {
            String target = con.getHeaderField("Location");
            if (target != null)
                return target;
        }
        return con.getURL().toString();

有人知道我做错了什么吗?

【问题讨论】:

    标签: java httpurlconnection http-redirect url-redirection


    【解决方案1】:

    服务器返回这个:

    <html>
    <head>
    <meta http-equiv="refresh" content="1; url=http://weeklyad.target.com">
    <title>Redirect</title>
    <script language="javascript" type="text/javascript">
    <!--
    function track_click(url)
    {
        var req = new Image();
        req.src = url;
    }
    
    function redirect(url)
    {
        window.location = url;
    }
    
    var url_raw = "http://weeklyad.target.com";
    var url_enc = "http%3A%2F%2Fweeklyad.target.com";
    
    track_click("http://track.pubmatic.com/AdServer/AdDisplayTrackerServlet?clickData=JnB1YklkPTIwOTc3JnNpdGVJZD0zMDE1MSZhZElkPTI2NjA0JmthZHNpemVpZD05JnRsZElkPTAmcGFzc2JhY2s9MCZjYW1wYWlnbklkPTEyMTYmY3JlYXRpdmVJZD0wJmFkU2VydmVySWQ9MjQz_url=" + url_enc);
    
    var redirect_timeout = 300;
    setTimeout('redirect("http://weeklyad.target.com")', redirect_timeout);
    // -->
    </script></head><body></body></html>
    

    所以重定向是因为调用了 redirect 函数 (javascript) 而不是 Location (header) 重定向。

    顺便说一句:您可以通过查看原始 URL 来了解您将到达的位置,注意 &amp;redirect=http://weeklyad.target.com 参数

    【讨论】:

    • 关于 'BTW' 备注:在这个特定示例中可能是这种情况,但在许多其他示例中并非如此;正如我所提到的,我需要一个通用的解决方案;当然——我只需要登陆页面的 URL,而不是整个页面内容;谢谢
    • 除非您完全模拟浏览器,而不仅仅是执行 HTTP GET,否则您将无法执行通用“解决方案”
    • 你是说我应该使用 Selenium 或类似的东西吗?
    • 是的,您需要在此处进行全浏览器仿真,或者处理 Location 和 JS 重定向,但您仍然可能会错过 META REFRESH,因此您也需要涵盖这一点,所以最好的选择是 selenium跨度>
    • 根据stackoverflow.com/a/5665218/1382251,即使是Selenium也可能无法做到这一点。
    猜你喜欢
    • 2014-01-15
    • 2017-09-22
    • 2016-09-15
    • 2017-06-12
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多