301永久移动

我正试图通过Java在URL中获取HTML。 但301 Moved Permanently就是我所拥有的一切。 另一个URL工作。 怎么了? 这是我的代码:

  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 } 

您正面临重定向到其他url的问题。 这很正常,网站可能有很多理由重定向您。 只需遵循基于“位置”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 HTTP客户端实现,例如Apache HTTP Client。 他们中的大多数都能够自动跟踪重定向。

您的代码没有任何问题。 该消息表示hh.ru永久移动到另一个域。

我测试了你的代码,没关系,但是当我使用“hh.ru”时,和你的问题一样,当我使用lynx(命令行浏览器)连接到“hh.ru”时,它会告诉我它正在重定向到另一个url,然后告诉我它已被永久移动,然后此警报:
“警报!:此客户端不包含对HTTPS URL的支持”

发现这个答案很有用,并且由于多次重定向的可能性而略有改进(例如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; } } 

当我在服务器上运行特定文件时,我解决了我的问题。 而不是http://hh.ru我使用http://hh.ru/index.php它对我有用