Example usage for javax.net.ssl HttpsURLConnection setInstanceFollowRedirects

List of usage examples for javax.net.ssl HttpsURLConnection setInstanceFollowRedirects

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadFile(final String url) throws IOException {
    InputStream in = null;/*from   w w w  .  j  a  v  a  2 s.c om*/
    OutputStream out = null;
    try {
        LOGGER.info("downloadFile: " + url);
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();
        if (urlc instanceof HttpsURLConnection) {
            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
        }
        in = urlc.getInputStream();//new GZIPInputStream(dbURL.openStream());
        //      if(sourceCompressed) { in = new GZIPInputStream(in); }

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadTM(final String url, final String authUrl, final String username,
        final String password, final int timeout) throws IOException {
    InputStream in = null;/*  w w w .  j  a v  a 2 s  .  c  o  m*/
    OutputStream out = null;

    try {
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();

        if (timeout != 0) {
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
        }

        if (urlc instanceof HttpsURLConnection) {
            final String cookie = getTmCookie(authUrl, username, password, timeout).toString();

            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
            http.addRequestProperty("Cookie", cookie);
        }

        in = urlc.getInputStream();

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

private static HttpCookie getTmCookie(final String url, final String username, final String password,
        final int timeout) throws IOException {
    if (tmCookie != null && !tmCookie.hasExpired()) {
        return tmCookie;
    }//w ww .  java2s . c  o m

    final String charset = UTF8_STR;
    final String query = String.format("u=%s&p=%s", URLEncoder.encode(username, charset),
            URLEncoder.encode(password, charset));
    final URLConnection connection = new URL(url).openConnection();

    if (!(connection instanceof HttpsURLConnection)) {
        return null;
    }

    final HttpsURLConnection http = (HttpsURLConnection) connection;

    http.setInstanceFollowRedirects(false);

    http.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    });

    http.setRequestMethod("POST");
    http.setAllowUserInteraction(true);

    if (timeout != 0) {
        http.setConnectTimeout(timeout);
        http.setReadTimeout(timeout);
    }

    http.setDoOutput(true); // Triggers POST.
    http.setRequestProperty("Accept-Charset", charset);
    http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

    OutputStream output = null;

    try {
        output = http.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
                LOGGER.debug(e, e);
            }
        }
    }

    LOGGER.info("fetching cookie: " + url);
    connection.connect();

    tmCookie = HttpCookie.parse(http.getHeaderField("Set-Cookie")).get(0);
    LOGGER.debug("cookie: " + tmCookie);

    return tmCookie;
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

public static JSONObject sendRequest(JSONObject request, String endpoint) {
    URL url;//from  ww  w  .  j a v a  2s .  c  o  m
    try {
        url = new URL(authServer + "/" + endpoint);
    } catch (MalformedURLException e) {
        return null;
    }
    try {
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setReadTimeout(5000);
        con.setConnectTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.connect();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
        try {
            request.writeJSONString(writer);
            writer.flush();
            writer.close();

            if (con.getResponseCode() != 200) {
                return null;
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            try {
                JSONParser parser = new JSONParser();

                try {
                    return (JSONObject) parser.parse(reader);
                } catch (ParseException e) {
                    return null;
                }
            } finally {
                reader.close();
            }
        } finally {
            writer.close();
            con.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;/*from  ww  w  .ja  va  2 s  .co m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setReadTimeout(5000);
    con.setConnectTimeout(5000);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.connect();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

private HttpsURLConnection createHttpUrlConnection(URL url) throws Exception {
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setHostnameVerifier(new TrustAllHosts());
    conn.setSSLSocketFactory(TrustAllCerts.createInsecureSslContext().getSocketFactory());
    conn.setInstanceFollowRedirects(false);
    String credentials = TEST_USERNAME + ":" + TEST_PASSWORD;
    conn.setRequestProperty("Authorization",
            "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
    return conn;/*w w  w.  jav  a2 s. c  om*/
}

From source file:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /*from   w  ww . ja va  2  s  . c o m*/
 * @param con ?HttpsURLConnection 
 * @return con option??HttpsURLConnection
 */
protected HttpsURLConnection setHttpHeader(HttpsURLConnection con) {
    try {
        con.setRequestMethod(this.method);
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setRequestProperty("Accept-Language", this.lang);
        con.setRequestProperty("Accept", this.accept);
        con.setRequestProperty("appid", this.appid);
        System.out.println("Accept: " + con.getRequestProperty("Accept"));
        System.out.println("appid: " + con.getRequestProperty("appid"));
        return con;
    } catch (ProtocolException e) {
        e.printStackTrace();
        return con;
    }
}

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;//w  w w .j ava  2  s. c  o  m

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}

From source file:in.rab.ordboken.NeClient.java

private void loginMainSite() throws IOException, LoginException {
    ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("_save_loginForm", "true"));
    data.add(new BasicNameValuePair("redir", "/success"));
    data.add(new BasicNameValuePair("redirFail", "/fail"));
    data.add(new BasicNameValuePair("userName", mUsername));
    data.add(new BasicNameValuePair("passWord", mPassword));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data);

    URL url = new URL("https://www.ne.se/user/login.jsp");
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setInstanceFollowRedirects(false);
    https.setFixedLengthStreamingMode((int) entity.getContentLength());
    https.setDoOutput(true);/*from  ww w  .ja  v  a2 s .  c  o  m*/

    try {
        OutputStream output = https.getOutputStream();
        entity.writeTo(output);
        output.close();

        Integer response = https.getResponseCode();
        if (response != 302) {
            throw new LoginException("Unexpected response: " + response);
        }

        String location = https.getHeaderField("Location");
        if (!location.contains("/success")) {
            throw new LoginException("Failed to login");
        }
    } finally {
        https.disconnect();
    }
}

From source file:org.openhab.binding.jablotron.internal.JablotronBinding.java

private void setConnectionDefaults(HttpsURLConnection connection) {
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("User-Agent", AGENT);
    connection.setRequestProperty("Accept-Language", "cs-CZ");
    connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
    connection.setUseCaches(false);//from ww  w  . j  a v a2s  .  co m
}