【问题标题】:how to follow redirected url in java?如何在java中跟踪重定向的url?
【发布时间】:2015-06-09 05:15:31
【问题描述】:

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

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

【问题讨论】:

  • 该 URL 返回 200 状态码。它不会重定向。所以没有重定向可以跟随。
  • @JBNizet 请在浏览器中查看此 URL。它将被重定向到另一个 URL。
  • 我有。两次。而且它不会重定向。
  • @JBNizet 我通过浏览器检查了重定向,似乎这个 URL 将重定向到 ubuntuforums.org/search.php?searchid=7345321
  • @JBNizet 似乎新的 url 是由服务器自动生成的

标签: java url-redirection http-redirect


【解决方案1】:

这对你的情况有帮助。

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

【讨论】:

  • 此方法不适用于示例 url。我提到的问题
  • 此代码块处于工作状态。我也用这个网址测试过graph.facebook.com/439873422836340/picture?type=large
  • 我认为我们必须为您的案例设置更具体的连接属性。
  • 当我运行connection.getHeaderField("Location") 时得到null。是不是意味着没有重定向?
猜你喜欢
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多