Java URL Connection getURLStream(URL url, int level)

Here you can find the source of getURLStream(URL url, int level)

Description

Get a stream to a URL accommodating possible redirections.

License

Open Source License

Declaration

public static InputStream getURLStream(URL url, int level)
        throws IOException 

Method Source Code

//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();
    }
}

Related

  1. getURLDataList(URL StrurlStringing)
  2. getUrlEncoding(URLConnection connection)
  3. getURLForward(URL url)
  4. getURLInputStream(final URL url)
  5. getUrlSource(String url)
  6. getWebPageHtmlContent(String url)
  7. getWebsiteContents(URL url)
  8. httpPost(String urlString, String postPath, Map keyValuePairs)
  9. imageFromUrl(String url)