Example usage for java.net HttpURLConnection setInstanceFollowRedirects

List of usage examples for java.net HttpURLConnection setInstanceFollowRedirects

Introduction

In this page you can find the example usage for java.net HttpURLConnection setInstanceFollowRedirects.

Prototype

public void setInstanceFollowRedirects(boolean followRedirects) 

Source Link

Document

Sets whether HTTP redirects (requests with response code 3xx) should be automatically followed by this HttpURLConnection instance.

Usage

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Prepares a connection to the server./*from  ww w.  j  av  a 2s .  c o m*/
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    con.setConnectTimeout(connectionTimeoutMillis);
    con.setReadTimeout(readTimeoutMillis);
    con.setAllowUserInteraction(false);
    con.setDefaultUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");

    // do stuff for ssl
    if (HttpsURLConnection.class.isInstance(con)) {
        HttpsURLConnection https = HttpsURLConnection.class.cast(con);
        if (hostNameVerifier != null) {
            https.setHostnameVerifier(hostNameVerifier);
        }
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    // add headers
    con.setRequestProperty("Content-Type", "application/json-rpc");
    for (Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : extraHeaders.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // return it
    return con;
}

From source file:org.dcm4che2.tool.dcmwado.DcmWado.java

private void fetch(String[] uids) {
    URL url = makeURL(uids);//from ww w  .j  a v  a  2s  .c  o  m
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(followsRedirect);
        con.setRequestProperty("Connection", "Keep-Alive");
        con.connect();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = con.getInputStream();
            if (dir != null) {
                out = new FileOutputStream(
                        outfile != null ? (outfile.isAbsolute() ? outfile : new File(dir, outfile.getPath()))
                                : new File(dir, uids[2] + toFileExt(con.getContentType())));
            }
            copy(in, out);
        } finally {
            CloseUtils.safeClose(out);
            CloseUtils.safeClose(in);
            if (noKeepAlive)
                con.disconnect();
        }
        System.out.print('.');
    } catch (Exception e) {
        System.err.println("ERROR: Failed to GET " + url + " - " + e.getMessage());
        e.printStackTrace();
        System.out.print('F');
    }
}

From source file:uk.ac.gate.cloud.client.RestClient.java

/**
 * Handles the sending side of an HTTP request, returning a connection
 * from which the response (or error) can be read.
 *//*from w  w  w.  j av a 2  s  .  c  o m*/
private HttpURLConnection sendRequest(String target, String method, Object requestBody, int gzipThreshold,
        String... extraHeaders) throws IOException {
    URL requestUrl = new URL(baseUrl, target);
    HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
    connection.setRequestMethod(method);
    connection.setInstanceFollowRedirects(false);
    if (authorizationHeader != null) {
        connection.setRequestProperty("Authorization", authorizationHeader);
    }
    boolean sentAccept = false;
    boolean sentContentType = false;
    if (extraHeaders != null) {
        for (int i = 0; i < extraHeaders.length; i++) {
            if ("Accept".equalsIgnoreCase(extraHeaders[i])) {
                sentAccept = true;
            }
            if ("Content-Type".equalsIgnoreCase(extraHeaders[i])) {
                sentContentType = true;
            }
            connection.setRequestProperty(extraHeaders[i], extraHeaders[++i]);
        }
    }
    if (!sentAccept) {
        connection.setRequestProperty("Accept", "application/json");
    }
    if (requestBody != null) {
        connection.setDoOutput(true);
        if (!sentContentType) {
            connection.setRequestProperty("Content-Type", "application/json");
        }
        OutputStream out;
        if (gzipThreshold >= 0) {
            out = new GZIPThresholdOutputStream(connection, gzipThreshold);
        } else {
            out = connection.getOutputStream();
        }
        try {
            if (requestBody instanceof InputStream) {
                IOUtils.copy((InputStream) requestBody, out);
            } else if (requestBody instanceof StreamWritable) {
                ((StreamWritable) requestBody).writeTo(out);
            } else {
                MAPPER.writeValue(out, requestBody);
            }
        } finally {
            out.close();
        }
    }
    return connection;
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Perform an HTTP GET request on a URL whose response is expected to
* be a 3xx redirection, and return the target redirection URL.
*
* @param source the URL to request (relative URLs will resolve against the {@link #getBaseUrl() base URL}).
* @return the URL returned by the "Location" header of the redirection response.
* @throws HttpClientException if an exception occurs during
*           processing, or the server returns a 4xx or 5xx error
*           response (in which case the response JSON message will be
*           available as a {@link JsonNode} in the exception), or if
*           the response was not a 3xx redirection.
*///from   w ww.ja v  a  2  s.  c  o m
public URL getRedirect(URL source) throws HttpClientException {
    try {
        HttpURLConnection connection = (HttpURLConnection) source.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", authorizationHeader);
        connection.setRequestProperty("Accept", "application/json");
        connection.setInstanceFollowRedirects(false);
        int responseCode = connection.getResponseCode();
        // make sure we read any response content
        readResponseOrError(connection, new TypeReference<JsonNode>() {
        }, false);
        if (responseCode >= 300 && responseCode < 400) {
            // it was a redirect
            String redirectUrl = connection.getHeaderField("Location");
            return new URL(redirectUrl);
        } else {
            throw new HttpClientException("Expected redirect but got " + responseCode);
        }
    } catch (IOException e) {
        throw new HttpClientException(e);
    }
}

From source file:socialtrade1.Engine.java

void Post() {

    try {//from   w w  w.  j  a va2  s.com

        byte[] postData = body.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;

        URL url1 = new URL(url);
        HttpURLConnection con = (HttpURLConnection) url1.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", " application/json; charset=UTF-8");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        con.setRequestProperty("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Host", "www.socialtrade.biz");
        con.setRequestProperty("Cookie", Cookie);
        con.setRequestProperty("Referer", "https://www.socialtrade.biz/User/TodayTask179.aspx");

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
        }
        response = response1.toString();

        in.close();
    } catch (Exception m) {

    }

}

From source file:socialtrade1.Engine1.java

void Post() {

    try {//from   www  . j a  v  a 2s .  com

        byte[] postData = body.getBytes(StandardCharsets.UTF_8);
        int postDataLength = postData.length;

        URL url1 = new URL(url);
        HttpURLConnection con = (HttpURLConnection) url1.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", " application/json; charset=UTF-8");
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        con.setRequestProperty("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        con.setRequestProperty("Host", "www.socialtrade.biz");
        con.setRequestProperty("Cookie", Cookie);
        con.setRequestProperty("Referer", "https://www.socialtrade.biz/User/TodayTask179.aspx");

        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response1 = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response1.append(inputLine);
        }

        response = response1.toString();

        in.close();
    } catch (Exception m) {

    }

}

From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testHttpRedirectToHttpss() throws Exception {
    Configuration conf = new Configuration();
    int httpPort = getRandomPort();
    int httpsPort = getRandomPort();
    String confDir = createTestDir();
    String keyStore = new File(confDir, "sdc-keystore.jks").getAbsolutePath();
    OutputStream os = new FileOutputStream(keyStore);
    IOUtils.copy(getClass().getClassLoader().getResourceAsStream("sdc-keystore.jks"), os);
    os.close();//w w  w .j a  v  a  2s .  co m
    conf.set(WebServerTask.AUTHENTICATION_KEY, "none");
    conf.set(WebServerTask.HTTP_PORT_KEY, httpPort);
    conf.set(WebServerTask.HTTPS_PORT_KEY, httpsPort);
    conf.set(WebServerTask.HTTPS_KEYSTORE_PATH_KEY, "sdc-keystore.jks");
    conf.set(WebServerTask.HTTPS_KEYSTORE_PASSWORD_KEY, "password");
    final WebServerTask ws = createWebServerTask(confDir, conf);
    try {
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);
        HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + httpPort + "/ping")
                .openConnection();
        conn.setInstanceFollowRedirects(false);
        Assert.assertTrue(conn.getResponseCode() >= 300 && conn.getResponseCode() < 400);
        Assert.assertTrue(conn.getHeaderField("Location").startsWith("https://"));
        HttpsURLConnection conns = (HttpsURLConnection) new URL(conn.getHeaderField("Location"))
                .openConnection();
        configureHttpsUrlConnection(conns);
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conns.getResponseCode());
    } finally {
        ws.stopTask();
    }
}

From source file:org.pocketcampus.plugin.moodle.server.old.MoodleServiceImpl.java

public MoodleSession getMoodleSession(TequilaToken iTequilaToken) throws TException {
    System.out.println("getMoodleSession");
    try {/*from   w w w.j  a  v a2 s .  c  o  m*/
        HttpURLConnection conn2 = (HttpURLConnection) new URL("http://moodle.epfl.ch/auth/tequila/index.php")
                .openConnection();
        conn2.setRequestProperty("Cookie", iTequilaToken.getLoginCookie());
        conn2.setInstanceFollowRedirects(false);
        conn2.getInputStream();
        if ("http://moodle.epfl.ch/my/".equals(conn2.getHeaderField("Location")))
            return new MoodleSession(iTequilaToken.getLoginCookie());
        else
            throw new TException("Authentication failed");
    } catch (IOException e) {
        e.printStackTrace();
        throw new TException("Failed to getMoodleSession from upstream server");
    }
}

From source file:org.owasp.dependencycheck.utils.URLConnectionFactory.java

/**
 * Utility method to create an HttpURLConnection. If the application is configured to use a proxy this method will retrieve
 * the proxy settings and use them when setting up the connection.
 *
 * @param url the url to connect to//from w  w w  . j a  v  a2s.c o  m
 * @return an HttpURLConnection
 * @throws URLConnectionFailureException thrown if there is an exception
 */
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Just being extra safe")
public static HttpURLConnection createHttpURLConnection(URL url) throws URLConnectionFailureException {
    HttpURLConnection conn = null;
    final String proxyUrl = Settings.getString(Settings.KEYS.PROXY_SERVER);

    try {
        if (proxyUrl != null && !matchNonProxy(url)) {
            final int proxyPort = Settings.getInt(Settings.KEYS.PROXY_PORT);
            final SocketAddress address = new InetSocketAddress(proxyUrl, proxyPort);

            final String username = Settings.getString(Settings.KEYS.PROXY_USERNAME);
            final String password = Settings.getString(Settings.KEYS.PROXY_PASSWORD);

            if (username != null && password != null) {
                final Authenticator auth = new Authenticator() {
                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        if (getRequestorType().equals(Authenticator.RequestorType.PROXY)) {
                            return new PasswordAuthentication(username, password.toCharArray());
                        }
                        return super.getPasswordAuthentication();
                    }
                };
                Authenticator.setDefault(auth);
            }

            final Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        final int timeout = Settings.getInt(Settings.KEYS.CONNECTION_TIMEOUT, 10000);
        conn.setConnectTimeout(timeout);
        conn.setInstanceFollowRedirects(true);
    } catch (IOException ex) {
        if (conn != null) {
            try {
                conn.disconnect();
            } finally {
                conn = null;
            }
        }
        throw new URLConnectionFailureException("Error getting connection.", ex);
    }
    return conn;
}

From source file:com.wareninja.android.opensource.mongolab_sdk.common.WebService.java

public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;//from w w  w .j  ava  2  s.  c om
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        mHttpResponseCode = response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception e) {
        throw new IOException("Error connecting");
    } // end try-catch

    return in;
}