如何在java中关注重定向的url?

我知道,对于在JAVA中跟踪重定向的URL,
java.net.httpURLConnection类可能会有所帮助.因此,为此目的实施以下方法:

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;

    }

我的问题是,此方法无法跟踪某些URL(例如以下URL)的重定向URL.但是,对于大多数重定向的URL,它可以正常工作.
http://ubuntuforums.org/search.php?do=getnew&contenttype=vBForum_Post

最佳答案

This can be 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;  }
点赞