301 Moved Permanently

怎甘沉沦 提交于 2019-12-30 10:40:49

问题


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


        }

回答1:


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);
}

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.




回答2:


found this answer useful and improved a little due to the possibility of multiple redirections (e.g. 307 then 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;
                    }
                }



回答3:


There's nothing wrong with your code. The message means that hh.ru is permanently moved to another domain.




回答4:


I tested your code and it is ok, but when I use "hh.ru", the same problem as yours, and when I use lynx(command line browser) to connect to "hh.ru", it will show me that it is redirecting to another url and then show me that it is moved permanently and after that this alert:
"Alert!: This client does not contain support for HTTPS URLs"




回答5:


Check if the URL provided is HTTP or HTTPS, consider adding protocol is you are using only domain name like http(s)://domainname.com/resource-name

Read: https://en.wikipedia.org/wiki/HTTP_301




回答6:


I resolved mine when I put the specific file running on the server. Instead of http://hh.ru, I used http://hh.ru/index.php. It worked for me



来源:https://stackoverflow.com/questions/18431440/301-moved-permanently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!