How to get redirected URL and content using HttpURLConnection

后端 未结 2 2100
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 17:41

Sometimes my URL will redirect to a new page, so I want to get the URL of the new page.

Here is my code:

URL url = new URL(\"http://stackoverflow.com         


        
相关标签:
2条回答
  • 2020-12-03 18:18

    actually we can use HttpClient, which we can set HttpClient.followRedirect(true) HttpClinent will handle the redirect things.

    0 讨论(0)
  • 2020-12-03 18:34

    Simply call getUrl() on URLConnection instance after calling getInputStream():

    URLConnection con = new URL(url).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();
    

    If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:

    HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
    con.setInstanceFollowRedirects(false);
    con.connect();
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);
    String location = con.getHeaderField("Location");
    System.out.println(location);
    
    0 讨论(0)
提交回复
热议问题