我试图在Java中通过URL获取HTML。但301 Moved Permanently是我的全部。另一个网址能用。怎么了?这是我的密码:
hh= new URL("http://hh.ru");
in = new BufferedReader(
new InputStreamReader(hh.openStream()));
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine).append("\n");
str=sb.toString();//returns 301
}发布于 2013-08-25 17:05:22
您正面临重定向到其他URL的问题。这是很正常的,网站可能有很多理由来重定向你。只需遵循基于"Location“HTTP头的重定向,如下所示:
URL hh= new URL("http://hh.ru");
URLConnection connection = hh.openConnection();
String redirect = connection.getHeaderField("Location");
if (redirect != null){
connection = new URL(redirect).openConnection();
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
System.out.println();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}您的浏览器是自动重定向的,但是使用URLConnection,您应该自己进行重定向。如果它困扰您,请查看其他Java客户端实现,比如Apache客户端。它们中的大多数都能够自动跟踪重定向。
发布于 2015-12-03 08:44:44
发现这个答案是有用的,并且由于多个重定向的可能性(例如307,然后301)而有所改进。
URLConnection urlConnection = url.openConnection();
String redirect = urlConnection.getHeaderField("Location");
for (int i = 0; i < MAX_REDIRECTS ; i++) {
if (redirect != null) {
urlConnection = new URL(redirect).openConnection();
redirect = urlConnection.getHeaderField("Location");
} else {
break;
}
}发布于 2013-08-25 17:02:10
你的代码没什么问题。该消息意味着hh.ru将永久移动到另一个域。
https://stackoverflow.com/questions/18431440
复制相似问题