Jsoup获取重定向的URL

Sor*_*ter 10 java url-shortener jsoup

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

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

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

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

Sya*_*m S 19

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

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

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

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

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