Java HttpURLConnection Open openConnectionCheckRedirects(URLConnection c)

Here you can find the source of openConnectionCheckRedirects(URLConnection c)

Description

open Connection Check Redirects

License

Apache License

Declaration

public static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class Main {
    public static InputStream openConnectionCheckRedirects(URLConnection c) throws IOException {
        boolean redir;
        int redirects = 0;
        InputStream in = null;//from  w w w.j ava2s .  c om
        do {
            if (c instanceof HttpURLConnection) {
                ((HttpURLConnection) c).setInstanceFollowRedirects(false);
            }
            // We want to open the input stream before getting headers
            // because getHeaderField() et al swallow IOExceptions.
            in = c.getInputStream();
            redir = false;
            if (c instanceof HttpURLConnection) {
                HttpURLConnection http = (HttpURLConnection) c;
                int stat = http.getResponseCode();
                if (stat >= 300 && stat <= 307 && stat != 306 && stat != HttpURLConnection.HTTP_NOT_MODIFIED) {
                    URL base = http.getURL();
                    String loc = http.getHeaderField("Location");
                    URL target = null;
                    if (loc != null) {
                        target = new URL(base, loc);
                    }
                    http.disconnect();
                    // Redirection should be allowed only for HTTP and HTTPS
                    // and should be limited to 5 redirections at most.
                    if (target == null
                            || !(target.getProtocol().equals("http") || target.getProtocol().equals("https"))
                            || redirects >= 5) {
                        throw new SecurityException("illegal URL redirect");
                    }
                    redir = true;
                    c = target.openConnection();
                    redirects++;
                }
            }
        } while (redir);
        return in;
    }
}

Related

  1. getConnectionStream(HttpURLConnection con)
  2. openConnection(final String urlString)
  3. openConnection(final URL url, final String requestMethod)
  4. openConnection(String url, String method, String contentType, String ssic)
  5. openConnection(URL url, Proxy proxy)