301永久移动 [英] 301 Moved Permanently
问题描述
我正在尝试通过Java中的URL获取HTML。但 301永久移动
就是我所拥有的一切。另一个URL工作。怎么了?这是我的代码:
I'm trying to get HTML by URL in Java. But 301 Moved Permanently
is all that I've got. Another URLs work. What's wrong? This is my code:
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
}
推荐答案
您正面临重定向到其他网址的问题。这很正常,网站可能有很多理由重定向您。只需遵循基于位置HTTP标头的重定向:
You're facing a redirect to other URL. It's quite normal and web site may have many reasons to redirect you. Just follow the redirect based on "Location" HTTP header like that:
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 HTTP客户端实施,例如Apache HTTP Client。他们中的大多数都能够自动关注重定向。
Your browser is following redirects automaticaly, but using URLConnection you should do it by your own. If it bothers you take a look at other Java HTTP client implementations, like Apache HTTP Client. Most of them are able to follow redirect automatically.
这篇关于301永久移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!