我想获取我感觉很幸运按钮重定向到的 URL(也称为第一个结果)。我传入 url:
http://www.google.com/search?&btnI=745&pws=0&q=hello
现在转到 http://www.hellomagazine.com/
问题是服务器用代码 200(OK)而不是 302(重定向)进行响应,所以我不知道重定向是如何执行的,也不知道如何获取最终 URL。
这是我一直在尝试的代码:
HttpURLConnection connection = (HttpURLConnection)wikiURL.openConnection();
connection.addRequestProperty("User-Agent", "Mozilla/4.76");
connection.setConnectTimeout(15000);
connection.setReadTimeout(15000);
connection.setInstanceFollowRedirects(false);
connection.connect();
System.out.println(connection.getResponseCode());
System.out.println(connection.getHeaderField("Location"));
这是输出:
200
null
编辑:问题似乎是 url 本身。它适用于我在这里发布的那个,但不适用于这个,例如:
“http://www.google.com/search?&btnI=745&pws=0&q=%2Bfutebolista+%2Bwikipedia+Marcio+Gabriel,+Atlético-GO”
最佳答案
如果我运行你的代码,我得到这个输出:
302
http://www.hellomagazine.com/
如果我设置
connection.setInstanceFollowRedirects(true);
然后我可以从
connection.getInputStream()
如果我将其保留为 false,即不遵循重定向,则输出为:
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.hellomagazine.com/">here</A>.
</BODY></HTML>
这有点奇怪,因为您正在阅读的 header 实际上并未设置!不过,您可以解析该正文并在收到 302 时查找 HREF,如果它仍然不适合您的话。
如果您仍然收到 200 响应,请尝试此操作并让我们知道输出是什么:
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
System.out.println(sb.toString());
我还设置了 Eclipse 的 TCP/IP 监视器,这样我就可以准确地看到通过网络发送的内容。
关于java - 跟随 google "I' m feeling lucky"使用 httpURLConnection 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6863877/