Jsoup获取重定向的URL [英] Jsoup get redirected URL

查看:2065
本文介绍了Jsoup获取重定向的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从网址缩短器提供的网址中获取实际(重定向)网址。

I'm trying to fetch the actual(redirected) url from the one provided by a url shortener.

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

Let's take twitter url shortener for example. I'm able to get the response object also parsed it to get the document.

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

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

Now, considering a single redirect, where to get the final url from? Any method or strategy to achieve this?

推荐答案

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

The Response object has a url() method which should give you the final url. So you could do like

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

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

If you want o get the intermediate redirects you should turn follow redirect off and then check for header "location". Eg

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

如果它有多个重定向,你需要递归调用网址。

If it has multiple redirect you need to recurssively call the urls.

这篇关于Jsoup获取重定向的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆