目前,我正在尝试使用Jsoup来获取此网址的最终重定向网址:https://playoverwatch.com/en-us/search?q=Lolzword-1298 。它应该重定向到此网址:https://playoverwatch.com/en-us/career/pc/us/Lolzword-1298 ,但下面的代码不会重定向 url。
String url = "https://playoverwatch.com/en-us/search?q=Lolzword-1298";
org.jsoup.Connection.Response response = Jsoup.connect(url).followRedirects(true).execute();
System.out.println(response.url());
有什么想法吗?
最佳答案
JSoup 的 followRedirects
用于 HTTP 重定向(“服务器重定向”),而您尝试使用的 URL 没有这样的东西。
包含您自己的问题的快捷方式 URL 的示例:
String url = "https://stackoverflow.com/q/44769507";
Connection.Response response = Jsoup.connect(url).followRedirects(true).execute();
System.out.println(response.url());
// https://stackoverflow.com/questions/44769507/jsoup-not-obtaining-final-redirected-url
由于 HTTP 重定向,这会打印不同的 URL,请参阅 header :
% curl -I 'https://stackoverflow.com/q/44769507'
HTTP/1.1 302 Found
Content-Type: text/html; charset=utf-8
Location: https://stackoverflow.com/questions/44769507/jsoup-not-obtaining-final-redirected-url
...
如果我尝试使用您的 URL,则不会出现 HTTP 重定向:
% curl -I 'https://playoverwatch.com/en-us/search?q=Lolzword-1298'
HTTP/1.1 200 OK
Cache-Control: public;max-age=300
Content-Length: 104248
Content-Type: text/html; charset=utf-8
...
当您加载页面时,您在浏览器中看到的“重定向”发生得更晚,使用 JavaScript(如果您在该页面上禁用 JavaScript,页面将保留在其原始位置),并且我认为 JSoup 无法捕获那个。
This answer指向 Selenium或HtmlUnit作为能够执行 JavaScript 并允许您获取最终 URL 的替代方案。
关于java - Jsoup 未获取最终重定向 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769507/