Android HttpURLConnection:处理HTTP重定向

时间:2013-04-02 01:25:10

标签: java android http redirect httpurlconnection

我正在使用HttpURLConnection来检索网址:

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

我现在想知道是否存在重定向,如果它是永久性的(301)或临时的(302),以便在第一种情况下更新数据库中的URL,而不是在第二种情况下更新。 / p>

这是否仍然可以使用HttpURLConnection的重定向处理以及if,如何?

2 个答案:

答案 0 :(得分:9)

致电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);

答案 1 :(得分:4)

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