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.ct855.util.HttpsClientUtil.java

public static String getUrl(String url)
        throws IOException, NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException {
    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL aURL = new java.net.URL(url);
    HttpsURLConnection aConnection = (HttpsURLConnection) aURL.openConnection();
    aConnection.setRequestProperty("Ocp-Apim-Subscription-Key", "d8400b4cdf104015bb23d7fe847352c8");
    aConnection.setSSLSocketFactory(ssf);
    aConnection.setDoOutput(true);/*from w ww.  jav a  2  s . c om*/
    aConnection.setDoInput(true);
    aConnection.setRequestMethod("GET");

    InputStream resultStream = aConnection.getInputStream();
    BufferedReader aReader = new java.io.BufferedReader(new java.io.InputStreamReader(resultStream));
    StringBuffer aResponse = new StringBuffer();
    String aLine = aReader.readLine();
    while (aLine != null) {
        aResponse.append(aLine + "\n");
        aLine = aReader.readLine();
    }
    resultStream.close();
    return aResponse.toString();
}

From source file:dictinsight.utils.io.HttpUtils.java

/**
 * https??post/*ww  w  .java 2  s  .  co  m*/
 * @param url
 * @param param
 * @return post?
 */
public static String httpsPostData(String url, String param) {
    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;
        }
    }

    BufferedOutputStream brOutStream = null;
    BufferedReader reader = null;

    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(1000 * 15);

        brOutStream = new BufferedOutputStream(connection.getOutputStream());
        brOutStream.write(param.getBytes());
        brOutStream.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseContent = "";
        String line = reader.readLine();
        while (line != null) {
            responseContent += line;
            line = reader.readLine();
        }

        return responseContent;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (brOutStream != null)
                brOutStream.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static ByteArrayOutputStream doGetImg(String url, String cookieStr) {
    InputStream in = null;/*from w w w . j  a  va  2s .  co m*/
    ByteArrayOutputStream outStream = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setRequestProperty("Cookie", cookieStr);
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.connect();
        in = conn.getInputStream();
        outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        conn.disconnect();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    return outStream;
}

From source file:com.ct855.util.HttpsClientUtil.java

public static String testIt(String https_url, Map<String, String> map, String method)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    //SSLContext??
    TrustManager[] trustAllCerts = new TrustManager[] { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    //SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();

    URL url;//from  w  w w .j a  va2  s .  c  om
    try {

        url = new URL(https_url);

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

        con.setRequestMethod(method);
        for (Map.Entry<String, String> entry : map.entrySet()) {
            con.setRequestProperty(entry.getKey(), entry.getValue());
        }

        con.setSSLSocketFactory(ssf);
        //dumpl all cert info
        //print_https_cert(con);
        //dump all the content
        return print_content(con);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

private static URL waitForDependency(URL url, String serviceName, String key, String value, String username,
        String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//  w ww  .j a v  a  2  s  .  c o m
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + url.getPath());
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH,
                                TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH,
                                CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    log.info(username + ":******");
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")"
                                + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")"
                            + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:org.talend.core.nexus.NexusServerUtils.java

private static HttpURLConnection getHttpURLConnection(String nexusUrl, String restService, String userName,
        String password) throws Exception {
    if (!nexusUrl.endsWith(NexusConstants.SLASH)) {
        nexusUrl = nexusUrl + NexusConstants.SLASH;
    }/*from ww  w.j av  a2 s  .  co  m*/
    URL url = new URL(nexusUrl + restService);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    if (urlConnection instanceof HttpsURLConnection) {
        String userDir = Platform.getInstallLocation().getURL().getPath();
        final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setSSLSocketFactory(socketFactory);
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });
    }
    IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE);
    int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000);
    urlConnection.setConnectTimeout(timeout);
    return urlConnection;
}

From source file:eu.siacs.conversations.ui.ServiceBrowserFragment.java

public static boolean exists(String URLName) {

    X509TrustManager trustManager = new X509TrustManager() {

        @Override/* w w w .  j av  a 2s  .c  o m*/
        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 {
        }
    };

    // 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) {
    }

    try {
        HttpsURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        URL url = new URL(URLName);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setSSLSocketFactory(noSSLv3Factory);
        con.setRequestProperty("Accept-Encoding", "");
        //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        con.setHostnameVerifier(new NullHostNameVerifier(url.getHost()));
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.talend.core.nexus.NexusServerUtils.java

/**
 * /*from  w w w.j  av  a2s . com*/
 * DOC check if the repository exist or not
 * 
 * @param nexusUrl
 * @param repositoryId
 * @param userName
 * @param password
 * @return
 */
public static boolean checkConnectionStatus(String nexusUrl, String repositoryId, final String userName,
        final String password) {
    if (StringUtils.isEmpty(nexusUrl)) {
        return false;
    }
    final Authenticator defaultAuthenticator = NetworkUtil.getDefaultAuthenticator();
    if (userName != null && !"".equals(userName)) {
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password.toCharArray());
            }

        });
    }
    int status = -1;
    try {
        if (nexusUrl == null || "".equals(nexusUrl) || repositoryId == null || "".equals(repositoryId)) {
            return false;
        }
        String newUrl = nexusUrl;
        if (newUrl.endsWith(NexusConstants.SLASH)) {
            newUrl = newUrl.substring(0, newUrl.length() - 1);
        }
        String urlToCheck = newUrl + NexusConstants.CONTENT_REPOSITORIES + repositoryId;

        URL url = new URL(urlToCheck);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            String userDir = Platform.getInstallLocation().getURL().getPath();
            final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
            HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
            httpsConnection.setSSLSocketFactory(socketFactory);
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

            });
        }
        IEclipsePreferences node = InstanceScope.INSTANCE.getNode(ORG_TALEND_DESIGNER_CORE);
        int timeout = node.getInt(ITalendCorePrefConstants.NEXUS_TIMEOUT, 10000);

        urlConnection.setConnectTimeout(timeout);
        urlConnection.setReadTimeout(timeout);
        status = urlConnection.getResponseCode();
        if (status == CONNECTION_OK) {
            return true;
        }
    } catch (Exception e) {
        ExceptionHandler.process(e);
    } finally {
        Authenticator.setDefault(defaultAuthenticator);
    }
    return false;
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;/*  www.  jav a2  s . c  o  m*/
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:info.guardianproject.netcipher.NetCipher.java

/**
 * Get a {@link HttpURLConnection} from a {@link URL}, and specify whether
 * it should use a more compatible, but less strong, suite of ciphers.
 *
 * @param url//from w  w w.  jav  a2  s .  c  o m
 * @param compatible
 * @return the {@code url} in an instance of {@link HttpURLConnection}
 * @throws IOException
 * @throws IllegalArgumentException if the proxy or TLS setup is incorrect
 */
public static HttpURLConnection getHttpURLConnection(URL url, boolean compatible) throws IOException {
    // .onion addresses only work via Tor, so force Tor for all of them
    Proxy proxy = NetCipher.proxy;
    if (OrbotHelper.isOnionAddress(url))
        proxy = ORBOT_HTTP_PROXY;

    HttpURLConnection connection;
    if (proxy != null) {
        connection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        connection = (HttpURLConnection) url.openConnection();
    }

    if (connection instanceof HttpsURLConnection) {
        HttpsURLConnection httpsConnection = ((HttpsURLConnection) connection);
        SSLSocketFactory tlsOnly = getTlsOnlySocketFactory(compatible);
        httpsConnection.setSSLSocketFactory(tlsOnly);
        if (Build.VERSION.SDK_INT < 16) {
            httpsConnection
                    .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        }
    }
    return connection;
}