java urlconnection get the final redirected URL

后端 未结 7 1821
死守一世寂寞
死守一世寂寞 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:19

    Try this, I using recursively to using for many redirection URL.

    public static String getFinalURL(String url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setInstanceFollowRedirects(false);
        con.connect();
        con.getInputStream();
    
        if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            String redirectUrl = con.getHeaderField("Location");
            return getFinalURL(redirectUrl);
        }
        return url;
    }
    

    and using:

    public static void main(String[] args) throws MalformedURLException, IOException {
        String fetchedUrl = getFinalURL("");
        System.out.println("FetchedURL is:" + fetchedUrl);
    
    }
    

提交回复
热议问题