Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

301 Moved Permanently

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


        }
like image 258
Tony Avatar asked Aug 25 '13 16:08

Tony


People also ask

What does 301 Moved Permanently?

The HyperText Transfer Protocol (HTTP) 301 Moved Permanently redirect status response code indicates that the requested resource has been definitively moved to the URL given by the Location headers. A browser redirects to the new URL and search engines update their links to the resource.

Are 301 redirects permanent?

301 redirects are permanent, whereas 302 redirects are temporary. A 301 is used when a page has permanently changed location, and a 302 should be used if you intend to move the page back under the original URL in the future.


2 Answers

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.

like image 152
Jk1 Avatar answered Oct 17 '22 15:10

Jk1


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;
                    }
                }
like image 2
Aviator Avatar answered Oct 17 '22 13:10

Aviator