Example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory

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

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setSSLSocketFactory.

Prototype

public void setSSLSocketFactory(SSLSocketFactory sf) 

Source Link

Document

Sets the <code>SSLSocketFactory</code> to be used when this instance creates sockets for secure https URL connections.

Usage

From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java

private HttpURLConnection configureConnection(HttpURLConnection conn) throws IOException {
    if (sslFactory != null) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {/*from w  w  w  .  j av a2  s. co m*/
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    return conn;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Tries to download the contents of the provided url using not commercially validated CA certificate from chosen provider.
 *
 * @param url_string as a string/*from   www.j a  v a2  s .c  o  m*/
 * @return an empty string if it fails, the url content if not.
 */
private String downloadWithProviderCA(String url_string) {
    String json_file_content = "";

    try {
        URL url = new URL(url_string);
        // Tell the URLConnection to use a SocketFactory from our SSLContext
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());
        if (!LeapSRPSession.getToken().isEmpty())
            urlConnection.addRequestProperty(LeapSRPSession.AUTHORIZATION_HEADER,
                    "Token token=" + LeapSRPSession.getToken());
        json_file_content = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        json_file_content = formatErrorMessage(R.string.certificate_error);
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchElementException e) {
        e.printStackTrace();
        json_file_content = formatErrorMessage(R.string.server_unreachable_message);
    }
    return json_file_content;
}

From source file:com.axibase.tsd.driver.jdbc.protocol.SdkProtocolImpl.java

private void doTrustToCertificates(final HttpsURLConnection sslConnection) {
    final SSLContext sslContext;
    try {/*from  w  ww .j av  a  2s. c o  m*/
        sslContext = SSLContext.getInstance(CONTEXT_INSTANCE_TYPE);
    } catch (NoSuchAlgorithmException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    final boolean trusted = contentDescription.isTrusted();
    if (logger.isDebugEnabled()) {
        logger.debug("[doTrustToCertificates] " + trusted);
    }
    try {
        sslContext.init(null, trusted ? DUMMY_TRUST_MANAGER : null, new SecureRandom());
    } catch (KeyManagementException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getMessage());
        }
        return;
    }
    sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());

    if (trusted) {
        sslConnection.setHostnameVerifier(DUMMY_HOSTNAME_VERIFIER);
    }
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

/**
 * Downloads the string that's in the url with any certificate.
 *///from w  w w.  j  a  v a  2  s  .co  m
private String downloadWithoutCA(String url_string) {
    String string = "";
    try {

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        class DefaultTrustManager implements X509TrustManager {

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL url = new URL(url_string);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(context.getSocketFactory());
        urlConnection.setHostnameVerifier(hostnameVerifier);
        string = new Scanner(urlConnection.getInputStream()).useDelimiter("\\A").next();
        System.out.println("String ignoring certificate = " + string);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        string = formatErrorMessage(R.string.malformed_url);
    } catch (IOException e) {
        // The downloaded certificate doesn't validate our https connection.
        e.printStackTrace();
        string = formatErrorMessage(R.string.certificate_error);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return string;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {//w  w  w.  j  av  a2s .  com
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/*from ww w. ja v  a 2  s.  c o m*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:org.apache.hadoop.yarn.client.cli.TopCLI.java

private URLConnection connect(URL url) throws Exception {
    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    AuthenticatedURL authUrl;// w  w w  .  ja  v  a 2 s .c  o m
    SSLFactory clientSslFactory;
    URLConnection connection;
    // If https is chosen, configures SSL client.
    if (YarnConfiguration.useHttps(getConf())) {
        clientSslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, getConf());
        clientSslFactory.init();
        SSLSocketFactory sslSocktFact = clientSslFactory.createSSLSocketFactory();

        authUrl = new AuthenticatedURL(new KerberosAuthenticator(), clientSslFactory);
        connection = authUrl.openConnection(url, token);
        HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
        httpsConn.setSSLSocketFactory(sslSocktFact);
    } else {
        authUrl = new AuthenticatedURL(new KerberosAuthenticator());
        connection = authUrl.openConnection(url, token);
    }
    connection.connect();
    return connection;
}

From source file:jp.primecloud.auto.sdk.Requester.java

protected HttpURLConnection createConnection(String url, PccOptions options)
        throws IOException, GeneralSecurityException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");

    if (options != null) {
        // HTTPS?
        if (connection instanceof HttpsURLConnection && Boolean.TRUE.equals(options.getIgnoreCerts())) {
            HttpsURLConnection connection2 = (HttpsURLConnection) connection;

            // ?//from  w ww.  ja v  a2 s.  c o  m
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            connection2.setSSLSocketFactory(sslcontext.getSocketFactory());

            // ???
            connection2.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }

    return connection;
}

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

private void configureHttpsUrlConnection(HttpsURLConnection conn) throws Exception {
    SSLContext sc = SSLContext.getInstance("SSL");
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }/*from   w  w  w  . j a  v a  2 s.  co m*/

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());
    conn.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private boolean logOut() {
    String delete_url = provider_api_url + "/logout";

    HttpsURLConnection urlConnection = null;
    int responseCode = 0;
    int progress = 0;
    try {//  www . j  a  va2 s.  com

        urlConnection = (HttpsURLConnection) new URL(delete_url).openConnection();
        urlConnection.setRequestMethod("DELETE");
        urlConnection.setSSLSocketFactory(getProviderSSLSocketFactory());

        responseCode = urlConnection.getResponseCode();
        broadcastProgress(progress++);
        LeapSRPSession.setToken("");
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IndexOutOfBoundsException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        try {
            if (urlConnection != null) {
                responseCode = urlConnection.getResponseCode();
                if (responseCode == 401) {
                    broadcastProgress(progress++);
                    LeapSRPSession.setToken("");
                    return true;
                }
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        e.printStackTrace();
        return false;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return true;
}