Avatar billede fredand Forsker
28. juni 2012 - 08:35 Der er 1 løsning

How to get correct html base url after forward?

Hello guys!

I'm playing around with some code that reads content from a URL like:

        URL nu;
        try {
           
            nu = new URL("http://www.nu/");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(nu.openStream()));

                    String inputLine;
                    while ((inputLine = in.readLine()) != null)
                        System.out.println(inputLine);
                    in.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

How ever I would like to detect the html base URL for the response.

If you go to http://www.nu/ in a browser you will see that there is a "forward" to the correct URL http://www.nunames.nu/

Is there a way to find out the "new" URL for the response?

I have tried like:

            System.out.println(nu.getHost());
            System.out.println(nu.getPath());
            System.out.println(nu.toURI().getHost());
            System.out.println(nu.toURI().getPath());

Best regards
Fredrik
Avatar billede fredand Forsker
28. juni 2012 - 08:50 #1
Hello!

Seems like this do the trick:

            URLConnection con = new URL( "http://www.nu/" ).openConnection();
            System.out.println( "orignal url: " + con.getURL() );
            con.connect();
            System.out.println( "connected url: " + con.getURL() );
            InputStream is = con.getInputStream();
            System.out.println( "redirected url: " + con.getURL() );
            is.close();

Found at:
http://stackoverflow.com/questions/2659000/java-how-to-find-the-redirected-url-of-a-url

Best regards
Fredrik
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester