Example usage for com.squareup.okhttp OkHttpClient setSslSocketFactory

List of usage examples for com.squareup.okhttp OkHttpClient setSslSocketFactory

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient setSslSocketFactory.

Prototype

public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory) 

Source Link

Document

Sets the socket factory used to secure HTTPS connections.

Usage

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@OnScheduled
public void setUpClient(final ProcessContext context) throws IOException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient okHttpClient = new OkHttpClient();

    // Add a proxy if set
    final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
    if (proxyHost != null && proxyPort != null) {
        final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        okHttpClient.setProxy(proxy);//from   w  ww  .  j  a  v  a2  s .  co m
    }

    // Set timeouts
    okHttpClient.setConnectTimeout(
            (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()),
            TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(
            context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(),
            TimeUnit.MILLISECONDS);

    // Set whether to follow redirects
    okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    }

    // check the trusted hostname property and override the HostnameVerifier
    String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
    if (!trustedHostname.isEmpty()) {
        okHttpClient.setHostnameVerifier(
                new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier()));
    }

    setAuthenticator(okHttpClient, context);

    useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean();

    okHttpClientAtomicReference.set(okHttpClient);
}

From source file:org.eyeseetea.malariacare.network.UnsafeOkHttpsClientFactory.java

License:Open Source License

public static OkHttpClient getUnsafeOkHttpClient() {
    try {/*from   w w w.  j a  v a  2  s. c o m*/
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

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

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

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

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.fineract.module.stellar.fineractadapter.RestAdapterProvider.java

License:Apache License

OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override/*from  w  ww  .  ja va 2s .  co  m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

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

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ignored) {
    }

    try {
        client.setHostnameVerifier((hostname, session) -> true);
        if (ctx != null) {
            client.setSslSocketFactory(ctx.getSocketFactory());
        }
    } catch (final Exception ignored) {
    }

    return client;
}

From source file:org.gdg.frisbee.android.api.GapiOkTransport.java

License:Apache License

@Override
protected GapiOkHttpRequest buildRequest(String method, String url) throws IOException {
    Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method);
    // connection with proxy settings
    URL connUrl = new URL(url);
    OkHttpClient client = new OkHttpClient();
    OkUrlFactory factory = new OkUrlFactory(client);
    SSLContext sslContext;/*  ww  w  .j a v  a2 s.c  om*/
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
    client.setSslSocketFactory(sslContext.getSocketFactory());

    if (proxy != null) {
        client.setProxy(proxy);
    }

    URLConnection conn = factory.open(connUrl);
    HttpURLConnection connection = (HttpURLConnection) conn;
    connection.setRequestMethod(method);

    return new GapiOkHttpRequest(connection);
}

From source file:org.gdg.frisbee.android.api.OkStack.java

License:Apache License

@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    OkUrlFactory factory = new OkUrlFactory(client);
    SSLContext sslContext;/*from www.j a  v a  2 s .c o m*/
    try {
        TrustManager[] trustAllCerts = new TrustManager[] {
                new GdgTrustManager(App.getInstance().getApplicationContext()) };

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
    client.setSslSocketFactory(sslContext.getSocketFactory());
    return factory.open(url);
}

From source file:org.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    if (ignoreSSLError) {
        client.setSslSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
    } else {/*from   www.  ja v a  2  s .com*/
        client.setSslSocketFactory(SSLCertificateSocketFactory.getDefault(0, null));
    }
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier());
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.getlantern.firetweet.util.net.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    final SSLCertificateSocketFactory sslSocketFactory;
    if (ignoreSSLError) {
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getInsecure(0, null);
    } else {/*  w w w . j  a  v a  2s . co  m*/
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new FiretweetTrustManager(context)});
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier(context, ignoreSSLError));
    client.setSslSocketFactory(sslSocketFactory);
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                Crashlytics.logException(e);

                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.hawkular.agent.monitor.util.BaseHttpClientGenerator.java

License:Apache License

public BaseHttpClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    /* set the timeouts explicitly only if they were set through the config */
    configuration.getConnectTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setConnectTimeout(timeout.intValue(), TimeUnit.SECONDS));
    configuration.getReadTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setReadTimeout(timeout.intValue(), TimeUnit.SECONDS));

    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }//w w  w .  j  a v  a  2  s  .  c o m
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.hawkular.client.android.util.WebSocketClientGenerator.java

License:Apache License

public WebSocketClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    if (configuration.getConnectTimeoutSeconds() != -1) {
        httpClient.setConnectTimeout(configuration.getConnectTimeoutSeconds(), TimeUnit.SECONDS);
    }/*from  w w w  . j av a  2  s  .  c  o  m*/

    if (configuration.getReadTimeoutSeconds() != -1) {
        httpClient.setReadTimeout(configuration.getReadTimeoutSeconds(), TimeUnit.SECONDS);
    }
    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.jclouds.docker.config.DockerOkHttpClientSupplier.java

License:Apache License

@Override
public OkHttpClient get() {
    OkHttpClient client = new OkHttpClient();
    ConnectionSpec tlsSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_0, TlsVersion.TLS_1_1, TlsVersion.TLS_1_2).build();
    ConnectionSpec cleartextSpec = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();
    client.setConnectionSpecs(ImmutableList.of(tlsSpec, cleartextSpec));
    // check if identity and credential are files, to set up sslContext
    if (new File(creds.get().identity).isFile() && new File(creds.get().credential).isFile()) {
        client.setSslSocketFactory(dockerSSLContextSupplier.get().getSocketFactory());
    }/*from ww w .jav  a2s .  co m*/
    return client;
}