我有一个Twitter缩短的URL(t.co),我正在尝试使用jsoup发送请求并解析其响应。在到达最终URL之前应该有三个重定向跃点。即使将followRedirects
设置为true
,使用jsoup也不是这种情况。
我的代码:
public static void main(String[] args) {
try {
Response response = Jsoup.connect("https://t. co/sLMy6zi4Yw").followRedirects(true).execute(); // Space intentional to avoid SOF shortened errors
System.out.println(response.statusCode()); // prints 200
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
但是,使用Python的Request库,我可以得到正确的响应:
response = requests.get('https://t. co/sLMy6zi4Yw', allow_redirects=False)
print(response.status_code)
301
我正在使用jsoup版本1.11.2和请求版本2.18.4与Python 3.5.2。
有人对此事有任何见解吗?
答案 0 :(得分:2)
要克服这种特殊情况,您可以删除Jsoup默认设置的User-Agent标头(出于某些未知/非文档原因)
Connection connection = Jsoup.connect(url).followRedirects(true);
connection.request().removeHeader("User-Agent");
让我们检查一下原始请求&查看服务器行为
请求用户代理(模拟浏览器)返回
卷曲示例
curl --include --raw "https://t. co/sLMy6zi4Yw" --user-agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
响应
Chrome / 63.0.3239.132 Safari / 537.36“
HTTP / 1.1 200确定
cache-control:private,max-age = 300
内容长度:257
content-security-policy:始终引用;
content-type:text / html;字符集= UTF-8
referrer-policy:unsafe-url
server:tsa_b
strict-transport-security:max-age = 0
变化:起源
x-response-time:20
x-xss-protection:1;模式=块;报告= https://twitter.com/i/xss_report
<head><meta name="referrer" content="always"><noscript><META http-equiv="refresh" content="0;URL=http://bit. ly/2n3VDpo"></noscript><title>http://bit. ly/2n3VDpo</title></head><script>window.opener = null;location.replace("http:\/\/bit. ly\/2n3VDpo")</script>
没有用户代理的请求返回
卷曲示例
curl --include --raw "https://t. co/sLMy6zi4Yw"
HTTP / 1.1 301永久移动
cache-control:private,max-age = 300
内容长度:0
位置:http://bit。 LY / 2n3VDpo
server:tsa_b
strict-transport-security:max-age = 0
变化:起源
x-response-time:9