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:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url//  www .j  a v  a2 s .co m
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

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

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:org.kontalk.upload.KontalkBoxUploadConnection.java

private void setupClient(HttpsURLConnection conn, String mime, boolean encrypted, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate,
            acceptAnyCertificate));//w  w w . j a v  a  2 s.c  om
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    if (encrypted)
        conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted");
    // bug caused by Lighttpd
    conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processDeleteRequest(URL url, String keyStore, String keyStorePassword)
        throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setRequestMethod("DELETE");
    con.addRequestProperty("x-ms-version", "2014-04-01");

    return con.getResponseCode();
}

From source file:org.jasig.cas.util.HttpClient.java

public boolean isValidEndPoint(final URL url) {
    HttpURLConnection connection = null;
    InputStream is = null;/*from w  ww .  java 2  s .c o m*/
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(this.connectionTimeout);
        connection.setReadTimeout(this.readTimeout);
        connection.setInstanceFollowRedirects(this.followRedirects);

        if (connection instanceof HttpsURLConnection) {
            final HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

            if (this.sslSocketFactory != null) {
                httpsConnection.setSSLSocketFactory(this.sslSocketFactory);
            }

            if (this.hostnameVerifier != null) {
                httpsConnection.setHostnameVerifier(this.hostnameVerifier);
            }
        }

        connection.connect();

        final int responseCode = connection.getResponseCode();

        for (final int acceptableCode : this.acceptableCodes) {
            if (responseCode == acceptableCode) {
                LOGGER.debug("Response code from server matched {}.", responseCode);
                return true;
            }
        }

        LOGGER.debug("Response Code did not match any of the acceptable response codes. Code returned was {}",
                responseCode);

        // if the response code is an error and we don't find that error acceptable above:
        if (responseCode == 500) {
            is = connection.getInputStream();
            final String value = IOUtils.toString(is);
            LOGGER.error("There was an error contacting the endpoint: {}; The error was:\n{}",
                    url.toExternalForm(), value);
        }
    } catch (final IOException e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
        if (connection != null) {
            connection.disconnect();
        }
    }
    return false;
}

From source file:net.roboconf.target.azure.internal.AzureIaasHandler.java

private int processPostRequest(URL url, byte[] data, String contentType, String keyStore,
        String keyStorePassword) throws GeneralSecurityException, IOException {

    SSLSocketFactory sslFactory = this.getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con;
    con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslFactory);
    con.setDoOutput(true);//from   w w  w . ja  va2  s.  c o  m
    con.setRequestMethod("POST");
    con.addRequestProperty("x-ms-version", "2014-04-01");
    con.setRequestProperty("Content-Length", String.valueOf(data.length));
    con.setRequestProperty("Content-Type", contentType);

    DataOutputStream requestStream = new DataOutputStream(con.getOutputStream());
    requestStream.write(data);
    requestStream.flush();
    requestStream.close();

    return con.getResponseCode();
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callGet(String stringUrl) {
    try {/*  w ww  .  j  a va2s.co m*/

        // Setup connection
        URL url = new URL(stringUrl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        //conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        // printHttpsCert(conn);
        conn.connect();
        int code = conn.getResponseCode();

        if (code >= 200 && code < 300) {
            String result = IOUtils.toString(conn.getInputStream());
            conn.disconnect();
            return new String[] { code + "", result };
        } else {
            conn.disconnect();
            return new String[] { code + "", "Server returned " + code + " response code" };
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callGet " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callGet " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public String callQueryFacility(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    // Setup connection
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);//  w  ww.j  a va  2  s  . c  o  m
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/* w w w. ja va2 s. c o  m*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

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

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

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

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public String callQueryFacility(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    Cohort singlePatientCohort = new Cohort();
    singlePatientCohort.addMember(e.getPatient().getId());

    Map<Integer, String> patientIdentifierMap = Context.getPatientSetService()
            .getPatientIdentifierStringsByType(singlePatientCohort, Context.getPatientService()
                    .getPatientIdentifierTypeByName(RHEAHL7Constants.IDENTIFIER_TYPE));

    // Setup connection
    String id = patientIdentifierMap.get(patientIdentifierMap.keySet().iterator().next());
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);/*from   ww  w  .j  a  v  a  2s .c  om*/
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();
    String headerValue = conn.getHeaderField("http.status");

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}