Jsoup获取重定向的URL

我正在尝试从url shortener提供的url中获取实际(重定向)url。

我们以twitter url shortener为例。 我能够得到响应对象也解析它以获取文档。

Response response = Jsoup.connect("http://t.co/i5dE1K4vSs") .followRedirects(true) //to follow redirects .execute(); 

现在,考虑单个重定向,从哪里获取最终的URL? 任何方法或策略来实现这一目标?

Response对象有一个url()方法,它应该为您提供最终的url。 所以你可以这样做

 String url = "http://t.co/i5dE1K4vSs"; Response response = Jsoup.connect(url).followRedirects(true).execute(); System.out.println(response.url()) 

如果你想获得中间重定向,你应该关闭重定向,然后检查标题“位置”。 例如

 String url = "http://t.co/i5dE1K4vSs"; Response response = Jsoup.connect(url).followRedirects(false).execute(); System.out.println(response.header("location")); 

如果它有多个重定向,则需要以递归方式调用URL。

码:

 String originalUrl = Jsoup.connect("http://t.co/i5dE1K4vSs") .followRedirects(true) //to follow redirects .execute().url().toExternalForm(); System.out.println(originalUrl); 

输出:

 http://ibnlive.in.com/news/messi-considered-move-to-arsenal/487799-5-21.html 

说明:

由于Connection.ResponseConnection.Base作为超接口,您可以使用它的#url()方法(然后根据需要使用URL对象)。