java urlconnection get the final redirected URL

后端 未结 7 1812
死守一世寂寞
死守一世寂寞 2020-11-30 13:07

I have a url which redirects to another url.I want to be able to get the final redirected URL.My code:

    public class testURLConnection
    {
    public st         


        
7条回答
  •  失恋的感觉
    2020-11-30 13:23

    @user719950 On my MAC-OSX - this solves the issue of truncated HTTP URL :

    To your original code , just add this below line : // You have to find through your browser what is the Request Header IE / Chrome is sending. I still dont have the explanation as why this simple setting is causing correct URL :)

    HttpURLConnection con =(HttpURLConnection) new URL
    ( "http://tinyurl.com/KindleWireless" ).openConnection();
     con.setInstanceFollowRedirects(true);
     con.setDoOutput(true);
      System.out.println( "orignal url: " + con.getURL() );     
             **con.setRequestProperty("User-Agent",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) 
        AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2  
       Safari/536.26.17");**                  
    
               con.connect();
        System.out.println( "connected url: " + con.getURL() );
        Thread.currentThread().sleep(2000l);
        InputStream is = con.getInputStream();
        System.out.println( "redirected url: " + con.getURL() );
    
        is.close();
    

提交回复
热议问题