10

我正在使用HttpURLConnection这样的方式检索 URL:

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
// ...

我现在想知道是否有重定向以及它是永久(301)还是临时(302),以便在第一种情况下更新数据库中的 URL,但在第二种情况下不更新。

这是否可能同时仍然使用重定向处理,HttpURLConnection如果,如何?

4

2 回答 2

10

getUrl()调用后只需调用URLConnection实例getInputStream()

URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();

如果您需要在实际获取其内容之前知道重定向是否发生,这里是示例代码:

HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);
于 2013-04-02T01:53:10.770 回答
7
private HttpURLConnection openConnection(String url) throws IOException {
    HttpURLConnection connection;
    boolean redirected;
    do {
        connection = (HttpURLConnection) new URL(url).openConnection();
        int code = connection.getResponseCode();
        redirected = code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER;
        if (redirected) {
            url = connection.getHeaderField("Location");
            connection.disconnect();
        }
    } while (redirected);
    return connection;
}
于 2017-07-22T10:36:01.723 回答