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.vuze.android.remote.AndroidUtils.java

private static boolean isURLAlive(String URLName, int conTimeout, int readTimeout) {
    try {/*from  w ww. j a v a  2  s .  c  om*/
        HttpURLConnection.setFollowRedirects(false);

        URL url = new URL(URLName);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection conHttps = (HttpsURLConnection) con;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() },
                        new SecureRandom());
                conHttps.setSSLSocketFactory(ctx.getSocketFactory());
            }

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

        con.setConnectTimeout(conTimeout);
        con.setReadTimeout(readTimeout);
        con.setRequestMethod("HEAD");
        con.getResponseCode();
        if (DEBUG) {
            Log.d(TAG, "isLive? conn result=" + con.getResponseCode() + ";" + con.getResponseMessage());
        }
        return true;
    } catch (Exception e) {
        if (DEBUG) {
            Log.e(TAG, "isLive " + URLName, e);
        }
        return false;
    }
}

From source file:org.openhab.binding.neato.internal.VendorVorwerk.java

/**
 * Trust the self signed certificate.//  ww  w  .j a v  a 2 s.com
 *
 * @param connection
 */
public void applyNucleoSslConfiguration(HttpsURLConnection connection) {
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(this.getClass().getClassLoader().getResourceAsStream("keystore.jks"),
                "geheim".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        connection.setSSLSocketFactory(sslctx.getSocketFactory());
    } 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();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.mapreduce.task.reduce.Fetcher.java

@VisibleForTesting
protected synchronized void openConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    if (sslShuffle) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
        try {//  ww w .  j  ava  2s. c  om
            httpsConn.setSSLSocketFactory(sslFactory.createSSLSocketFactory());
        } catch (GeneralSecurityException ex) {
            throw new IOException(ex);
        }
        httpsConn.setHostnameVerifier(sslFactory.getHostnameVerifier());
    }
    connection = conn;
}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String payurl, String method, String strlength) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(payurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);
    conn.setRequestMethod(method);/* w ww. j  a va 2 s .com*/
    conn.setRequestProperty("Host", "mypay.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    conn.setRequestProperty("Referer", payurl);
    conn.setRequestProperty("Connection", "keep-alive");
    // conn.setRequestProperty("Pragma", "no-cache");
    // conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setRequestProperty("Content-Length", strlength);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String httpsurl) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(httpsurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);
    conn.setRequestMethod("GET");
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }/*from  w ww.  j a v a 2  s .c  o  m*/
    conn.setRequestProperty("Host", "security.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Pragma", "no-cache");
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:org.wso2.carbon.identity.authenticator.PushAuthentication.java

/**
 * Prompt for a login and an OTP./* w w w.  j  a  v  a 2  s .c o  m*/
 */
public JSONObject pushAuthenticate(String userId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=pushAuthenticate" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = setHttpsClientCert(this.p12file, this.p12password);
        }
        SSLSocketFactory sslsocketfactory = context.getSocketFactory();
        URL url = new URL(urlString + urlParameters);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING));
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(br);

    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e);
    } catch (MalformedURLException e) {
        throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e);
    } catch (ParseException e) {
        throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e);
    } catch (Exception e) {
        throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e);
        }
    }
    return json;
}

From source file:org.bremersee.sms.GoyyaSmsService.java

/**
 * Creates the URL connection./*www.j a  v  a 2s . c  om*/
 * 
 * @param url
 *            the URL
 * @return the URL connection
 * @throws IOException
 *             if creation of the URL connection fails
 */
protected HttpURLConnection createHttpURLConnection(final String url) throws IOException {

    URL sendUrl = new URL(url);

    HttpURLConnection con = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) {

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        con = (HttpURLConnection) sendUrl.openConnection(proxy);
        if (StringUtils.isNotBlank(proxyUsername)) {
            String passwd = proxyPassword != null ? proxyPassword : "";
            String authValue = proxyUsername + ":" + passwd;
            String headerValue = Base64.encodeBase64String(authValue.getBytes("utf-8"));
            con.setRequestProperty("Proxy-Authorization", "Basic " + headerValue);
        }

    } else {

        con = (HttpURLConnection) sendUrl.openConnection();
    }

    try {
        if (url.toString().toLowerCase().startsWith("https")) {
            HttpsURLConnection secCon = (HttpsURLConnection) con;
            secCon.setHostnameVerifier(createAllHostnamesVerifier());
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, createTrustAllManagers(), new SecureRandom());
            secCon.setSSLSocketFactory(sc.getSocketFactory());
        }

    } catch (NoSuchAlgorithmException e) {
        IOException ise = new IOException(e);
        // log.error("Creating HttpURLConnection failed.", ise);
        throw ise;

    } catch (KeyManagementException e) {
        IOException ise = new IOException(e);
        // log.error("Creating HttpURLConnection failed.", ise);
        throw ise;
    }

    return con;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private String getPEMCertificateFromServer(String host) {
    HttpsURLConnection connection = null;
    try {//from  w  w w .  ja va  2  s.c om
        URL url = new URL(host);

        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(hostnameVerifier);
        connection.setSSLSocketFactory(generateSSLContextWhichAcceptAllSSLCertificats());
        connection.connect();

        java.security.cert.Certificate[] cert = connection.getServerCertificates();
        connection.disconnect();

        byte[] by = ((X509Certificate) cert[0]).getEncoded();
        if (by.length != 0) {
            return BEGIN_CERT + Base64.getEncoder().encodeToString(by) + END_CERT;
        }
    } catch (MalformedURLException e) {
        if (!informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION)) {
            logger.error("A MalformedURLException occurred: ", e);
        }
    } catch (IOException e) {
        short code = ConnectionManager.GENERAL_EXCEPTION;
        if (e instanceof java.net.ConnectException) {
            code = ConnectionManager.CONNECTION_EXCEPTION;
        } else if (e instanceof java.net.UnknownHostException) {
            code = ConnectionManager.UNKNOWN_HOST_EXCEPTION;
        }
        if (!informConnectionManager(code) || code == -1) {
            logger.error("An IOException occurred: ", e);
        }
    } catch (CertificateEncodingException e) {
        logger.error("A CertificateEncodingException occurred: ", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:com.tc.util.io.ServerURL.java

private static void tweakSecureConnectionSettings(URLConnection urlConnection) {
    HttpsURLConnection sslUrlConnection;

    try {//from w  w w .  j a  va  2s .  c o  m
        sslUrlConnection = (HttpsURLConnection) urlConnection;
    } catch (ClassCastException e) {
        throw new IllegalStateException("Unable to cast " + urlConnection
                + " to javax.net.ssl.HttpsURLConnection. "
                + "Options tc.ssl.trustAllCerts and tc.ssl.disableHostnameVerifier are causing this issue.", e);
    }

    if (DISABLE_HOSTNAME_VERIFIER) {
        // don't verify hostname
        sslUrlConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

    TrustManager[] trustManagers = null;
    if (TRUST_ALL_CERTS) {
        // trust all certs
        trustManagers = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

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

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        sslUrlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException("unable to create SSL connection from " + urlConnection.getURL(), e);
    }
}