HttpURLConnection in its design will not automatically redirect from HTTP to HTTPS (or vice versa). After a redirect, serious security implications can occur. SSL (hence, HTTPS) creates a session that is unique to the user. This session can be reused for multiple requests. Thus, the server can track all requests made from one person. This is a weak form of identity and can be used. In addition, SSL handshake can request a client certificate. If sent to the server, the client identifier is transmitted to the server.
As Erickson points out, suppose the application is configured to automatically authenticate the client. The user expects anonymous surfing because he uses HTTP. But if his client follows HTTPS without a request, his identity is revealed on the server.
With this I realized, here is the code that will follow the redirects.
URL resourceUrl, base, next; Map<String, Integer> visited; HttpURLConnection conn; String location; int times; ... visited = new HashMap<>(); while (true) { times = visited.compute(url, (key, count) -> count == null ? 1 : count + 1); if (times > 3) throw new IOException("Stuck in redirect loop"); resourceUrl = new URL(url); conn = (HttpURLConnection) resourceUrl.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setInstanceFollowRedirects(false); // Make the logic below easier to detect redirections conn.setRequestProperty("User-Agent", "Mozilla/5.0..."); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: location = conn.getHeaderField("Location"); location = URLDecoder.decode(location, "UTF-8"); base = new URL(url); next = new URL(base, location); // Deal with relative URLs url = next.toExternalForm(); continue; } break; } is = conn.openStream(); ...
Nathan Sep 25 '14 at 18:59 2014-09-25 18:59
source share