Android HttpURLConnection:处理HTTP重定向

Jul*_*ian 10 java redirect android http httpurlconnection

我正在使用如下HttpURLConnection检索URL:

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
// ...
Run Code Online (Sandbox Code Playgroud)

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

这仍然可以使用重定向处理HttpURLConnection和if,如何?

syb*_*0rg 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();
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)


dan*_*nik 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;
}
Run Code Online (Sandbox Code Playgroud)