Java URL Redirect getRedirectedUrl(String url)

Here you can find the source of getRedirectedUrl(String url)

Description

get Redirected Url

License

LGPL

Declaration

public static String getRedirectedUrl(String url) throws MalformedURLException, IOException 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;

import java.net.URL;

public class Main {
    public static String getRedirectedUrl(String url) throws MalformedURLException, IOException {
        HttpURLConnection connection;
        String finalUrl = url;//from   w  w  w .  ja va2  s  .  co m
        do {
            connection = (HttpURLConnection) new URL(finalUrl).openConnection();
            connection.setInstanceFollowRedirects(false);
            connection.setUseCaches(false);
            connection.setRequestMethod("GET");
            connection.connect();
            int responseCode = connection.getResponseCode();
            if (responseCode >= 300 && responseCode < 400) {
                String redirectedUrl = connection.getHeaderField("Location");
                if (redirectedUrl == null)
                    break;
                finalUrl = redirectedUrl;
            } else
                break;
        } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
        connection.disconnect();
        return finalUrl.replaceAll(" ", "%20");
    }
}

Related

  1. getRedirectUrl(final URL url)