使用Java / HttpURLConnection检索特定URL的重定向URL

时间:2013-12-28 19:31:14

标签: java httpurlconnection http-redirect url-redirection

如何获取以下网址的“最终位置”(a.k.a. landing-page):

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”,但我只是得到相同的网址。

无需提及,我无法解决这个具体案例,但我仍然需要一般解决方案。

这是我的简单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();

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

1 个答案:

答案 0 :(得分: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(标题)重定向。

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