Android HttpURLConnection: Handle HTTP redirects

后端 未结 2 1199
一生所求
一生所求 2020-12-31 11:49

I\'m using HttpURLConnection to retrieve an URL just like that:

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) u         


        
2条回答
  •  忘掉有多难
    2020-12-31 12:33

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

提交回复
热议问题