Example usage for javax.net.ssl SSLContext getInstance

List of usage examples for javax.net.ssl SSLContext getInstance

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getInstance.

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;/* www  .  ja va  2 s.  c o m*/

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:client.lib.Client.java

public Client() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
            return myTrustedAnchors;
        }//from w w  w.  j a  v  a2  s. c  o  m

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    http2Client = new OkHttpClient();
    http2Client.setSslSocketFactory(sslSocketFactory);
    http2Client.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    httpClient = http2Client.clone();

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}

From source file:com.voa.weixin.utils.HttpUtils.java

/**
 * httpspost?/*  www  . j a  v  a 2 s  .  c  o m*/
 * 
 * @param url
 * @param param
 * @return
 * @throws Exception
 */
private static String doHttps(String url, String param, String method) throws Exception {
    HttpsURLConnection conn = null;
    OutputStream out = null;
    String rsp = null;
    byte[] content = param.getBytes("utf-8");
    try {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
            SSLContext.setDefault(ctx);

            conn = getConnection(new URL(url), method, ctype);
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
        } catch (Exception e) {
            throw e;
        }
        try {
            out = conn.getOutputStream();
            if (StringUtils.isNotBlank(param))
                out.write(content);
            rsp = getResponseAsString(conn);
        } catch (IOException e) {
            throw e;
        }

    } finally {
        if (out != null) {
            out.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return rsp;
}

From source file:com.googlecode.noweco.webmail.httpclient.UnsecureHttpClientFactory.java

public DefaultHttpClient createUnsecureHttpClient(final HttpHost proxy) {
    DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    SchemeRegistry schemeRegistry = httpclient.getConnectionManager().getSchemeRegistry();
    schemeRegistry.unregister("https");
    try {/*from  w ww.ja  v a  2 s. co  m*/
        SSLContext instance = SSLContext.getInstance("TLS");
        TrustManager tm = UnsecureX509TrustManager.INSTANCE;
        instance.init(null, new TrustManager[] { tm }, null);
        schemeRegistry.register(new Scheme("https", 443,
                new SSLSocketFactory(instance, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)));
    } catch (Exception e) {
        throw new RuntimeException("TLS issue", e);
    }
    httpclient.removeResponseInterceptorByClass(ResponseProcessCookies.class);
    httpclient.addResponseInterceptor(new UnsecureResponseProcessCookies());
    HttpParams params = httpclient.getParams();
    if (proxy != null) {
        ConnRouteParams.setDefaultProxy(params, proxy);
    }
    HttpConnectionParams.setSoTimeout(params, 7000);
    return httpclient;
}

From source file:cn.geowind.takeout.verify.CcopHttpClient.java

/**
 * SSL//from  w  w  w  . j  a  v  a  2  s  .c o  m
 * 
 * @param hostname
 *            ??IP??
 * @param protocol
 *            ????TLS-??
 * @param port
 *            ??
 * @param scheme
 *            ????
 * @return HttpClient
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public DefaultHttpClient registerSSL(String hostname, String protocol, int port, String scheme)
        throws NoSuchAlgorithmException, KeyManagementException {

    // HttpClient
    DefaultHttpClient httpclient = new DefaultHttpClient();
    // SSL
    SSLContext ctx = SSLContext.getInstance(protocol);
    // ???
    X509TrustManager tm = new X509TrustManager() {
        /**
         * CA??
         */
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        /**
         * ???
         * 
         * @param chain
         *            ?
         * @param authType
         *            ???authTypeRSA
         */
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain == null || chain.length == 0)
                throw new IllegalArgumentException("null or zero-length certificate chain");
            if (authType == null || authType.length() == 0)
                throw new IllegalArgumentException("null or zero-length authentication type");

            boolean br = false;
            Principal principal = null;
            for (X509Certificate x509Certificate : chain) {
                principal = x509Certificate.getSubjectX500Principal();
                if (principal != null) {
                    br = true;
                    return;
                }
            }
            if (!br) {
                throw new CertificateException("????");
            }
        }

        /**
         * ??
         */
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }
    };

    // ?SSL
    ctx.init(null, new TrustManager[] { tm }, new java.security.SecureRandom());
    // SSL
    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme(scheme, port, socketFactory);
    // SSL
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    return httpclient;
}

From source file:br.com.ararati.operacoes.SocketFactory.java

private SSLContext createSSLContext() {
    try {/*from  w ww.j a v  a 2  s. c o m*/
        KeyManager[] keyManagers = createKeyManagers();
        TrustManager[] trustManagers = createTrustManagers();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);

        return sslContext;
    } catch (KeyManagementException e) {
        error(e.toString());
    } catch (KeyStoreException e) {
        error(e.toString());
    } catch (NoSuchAlgorithmException e) {
        error(e.toString());
    } catch (CertificateException e) {
        error(e.toString());
    } catch (IOException e) {
        error(e.toString());
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.ssl.InsecureSSLProtocolSocketFactory.java

/**
 * Creates a new insecure SSL protocol socket factory.
 *
 * @throws GeneralSecurityException if a security error occurs
 *//* www  .  jav  a 2  s. co m*/
public InsecureSSLProtocolSocketFactory() throws GeneralSecurityException {
    context_ = SSLContext.getInstance("SSL");
    context_.init(null, new TrustManager[] { new InsecureTrustManager() }, null);
}

From source file:com.sparkplatform.api.core.HttpClientTest.java

@Test
public void testSSL() throws Exception {

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new ConnectionApacheHttps.FullTrustManager() }, null);
    HttpClient c = new DefaultHttpClient();
    //SSLSocketFactory sf = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
    @SuppressWarnings("deprecation")
    Scheme https = new Scheme("https", sf, 443);
    c.getConnectionManager().getSchemeRegistry().register(https);
    HttpHost h = new HttpHost("api.flexmls.com", 443, "https");

    HttpRequest r = new HttpGet("/v1/");
    HttpResponse rs = c.execute(h, r);/*from w w  w  . j a  v a  2  s .c  o m*/

    assertEquals(404, rs.getStatusLine().getStatusCode());
    String s = readString(rs.getEntity().getContent());
    assertEquals(s, "{\"D\":{\"Success\":false,\"Code\":404,\"Message\":\"Not Found\"}}");
}

From source file:org.sana.net.http.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(TrustManager manager) throws IOException {
    try {/*from  w w  w. j a va  2s  . com*/
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { manager }, null);
        return context;
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:ui.shared.FreebaseHelper.java

@SuppressWarnings("deprecation")
public static HttpClient wrapClient(HttpClient base) {
    try {/*from www .ja va 2 s . co  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            public boolean verify(String string, SSLSession ssls) {
                return true;
            }

        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}