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

时间:2015-04-04 06:53:06

标签: java url-redirection http-redirect

我知道在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;

    }

我的问题是,此方法无法跟踪某些网址(例如以下网址)的重定向网址,但它适用于大多数重定向网址。 http://ubuntuforums.org/search.php?do=getnew&contenttype=vBForum_Post

1 个答案:

答案 0 :(得分:2)

  

这可以帮助您。

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;  }