java – 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.
标签:java,jsoup,url-shortener 来源: https://codeday.me/bug/20191001/1837944.html