Here you can find the source of getURLStream(URL url, int level)
public static InputStream getURLStream(URL url, int level) throws IOException
//package com.java2s; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class Main { /**/*from w w w. j a v a 2s . c o m*/ * Get a stream to a URL accommodating possible redirections. Note that if a * redirection request points to a different protocol than the original * request, then the redirection is not handled automatically. */ public static InputStream getURLStream(URL url, int level) throws IOException { // Hard coded....sigh if (level > 5) { throw new IOException("Two many levels of redirection in URL"); } URLConnection conn = url.openConnection(); // Map<String,List<String>> hdrs = conn.getHeaderFields(); Map hdrs = conn.getHeaderFields(); // Read through the headers and see if there is a redirection header. // We loop (rather than just do a get on hdrs) // since we want to match without regard to case. String[] keys = (String[]) hdrs.keySet().toArray(new String[0]); // for (String key: hdrs.keySet()) { for (String key : keys) { if (key != null && key.toLowerCase().equals("location")) { // String val = hdrs.get(key).get(0); String val = (String) ((List) hdrs.get(key)).get(0); if (val != null) { val = val.trim(); if (val.length() > 0) { // Redirect return getURLStream(new URL(val), level + 1); } } } } // No redirection return conn.getInputStream(); } }