How to follow a redirected URL in java?

I know that for the following redirected URLs in JAVA, the java.net.httpURLConnection class may be useful. Therefore, for this purpose, the following method is implemented:

public static String getRedirectedUrl(String url) throws IOException {
        HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.setRequestProperty("User-Agent", "Googlebot");
        con.setInstanceFollowRedirects(false);
        con.connect();
        String headerField = con.getHeaderField("Location");
        return headerField == null ? url : headerField;

    }

My problem is that this method cannot track the redirected URLs for some URLs, such as the following URL. However, it is great for most redirected URLs. http://ubuntuforums.org/search.php?do=getnew&contenttype=vBForum_Post

+4
source share
1 answer

This may help you in your case.

public static String getFinalRedirectedUrl(String url)  {       
        String finalRedirectedUrl = url;
        try {
            HttpURLConnection connection;
            do {
                    connection = (HttpURLConnection) new URL(finalRedirectedUrl).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(null== redirectedUrl) {
                            break;
                        }
                        finalRedirectedUrl =redirectedUrl;
                    }
                    else
                        break;
            } while (connection.getResponseCode() != HttpURLConnection.HTTP_OK);
            connection.disconnect();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return finalRedirectedUrl;  }
+2
source

All Articles