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.mariotaku.twidere.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 {/*from  w w w  .j a  va 2  s  . c o  m*/
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new TwidereTrustManager(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) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.mifos.module.sms.provider.RestAdapterProvider.java

License:Apache License

@SuppressWarnings("unused")
public OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

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

        @Override//from   ww  w  . j av a 2 s  .  c  o 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 ex) {
    }

    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
    }

    return client;
}

From source file:org.mifos.tools.provider.RestAdapterProvider.java

License:Mozilla Public License

private OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

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

        @Override/*  w ww  . j  av a2s . com*/
        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 ex) {
        // do nothing, ignore
    }

    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
        // do nothing, ignore
    }

    return client;
}

From source file:org.perfcake.reporting.destination.InfluxDbDestination.java

License:Apache License

@Override
public void open() {
    Arrays.stream(tags.split(",")).map(StringUtil::trim).forEach(tagsArray::add);

    try {// ww w.j a va 2 s.  com
        if ((keyStore != null && !"".equals(keyStore)) || (trustStore != null && !"".equals(trustStore))) {
            sslFactory = SslSocketFactoryFactory.newSslSocketFactory(keyStore, keyStorePassword, trustStore,
                    trustStorePassword);
        }
    } catch (PerfCakeException e) {
        log.warn("Unable to initialize SSL socket factory: ", e);
    }

    try {
        if (sslFactory != null) {
            final OkHttpClient client = new OkHttpClient();
            client.setSslSocketFactory(sslFactory);
            client.setHostnameVerifier((hostname, session) -> true);
            influxDb = InfluxDBFactory.connect(serverUrl, userName, password, new OkClient(client));
        } else {
            influxDb = InfluxDBFactory.connect(serverUrl, userName, password);
        }
        if (createDatabase) {
            influxDb.createDatabase(database);
        }
        influxDb.enableBatch(100, 500, TimeUnit.MILLISECONDS);
    } catch (RuntimeException rte) {
        influxDb = null;
        log.error("Unable to connect to InfluxDb: ", rte);
    }
}

From source file:org.sonar.runner.impl.OkHttpClientFactory.java

License:Open Source License

static OkHttpClient create(JavaVersion javaVersion) {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setConnectTimeout(CONNECT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    httpClient.setReadTimeout(READ_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions()
            .allEnabledCipherSuites().supportsTlsExtensions(true).build();
    httpClient.setConnectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    if (javaVersion.isJava7()) {
        // OkHttp executes SSLContext.getInstance("TLS") by default (see
        // https://github.com/square/okhttp/blob/c358656/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java#L616)
        // As only TLS 1.0 is enabled by default in Java 7, the SSLContextFactory must be changed
        // in order to support all versions from 1.0 to 1.2.
        // Note that this is not overridden for Java 8 as TLS 1.2 is enabled by default.
        // Keeping getInstance("TLS") allows to support potential future versions of TLS on Java 8.
        try {//from  w  w  w .  j a va2  s  .c o  m
            httpClient.setSslSocketFactory(
                    new Tls12Java7SocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault()));
        } catch (Exception e) {
            throw new IllegalStateException("Fail to init TLS context", e);
        }
    }
    return httpClient;
}

From source file:org.tecrash.crashreport.DropboxUploadingJob.java

License:Open Source License

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    //        client.networkInterceptors().add(new GzipRequestInterceptor());
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override//from  w  ww .j  a  v a 2s  .c  om
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = sslContext.getSocketFactory();
        client.setSslSocketFactory(sf);
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }
    return client;
}

From source file:org.tecrash.crashreport.UptimeJob.java

License:Open Source License

private OkHttpClient getClient() {
    OkHttpClient client = new OkHttpClient();
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override//from   w  w  w  .  j  a  v  a 2s .co m
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } }, new SecureRandom());

        SSLSocketFactory sf = sslContext.getSocketFactory();
        client.setSslSocketFactory(sf);
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }
    return client;
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private Response getConnection(String urlFragment, String method, String body) throws PushNetworkException {
    try {/*from   w  ww .  j  a  v a 2  s  .  c  om*/
        Log.w(TAG, "Push service URL: " + serviceUrl);
        Log.w(TAG, "Opening URL: " + String.format("%s%s", serviceUrl, urlFragment));

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setSslSocketFactory(context.getSocketFactory());
        okHttpClient.setHostnameVerifier(new StrictHostnameVerifier());

        Request.Builder request = new Request.Builder();
        request.url(String.format("%s%s", serviceUrl, urlFragment));

        if (body != null) {
            request.method(method, RequestBody.create(MediaType.parse("application/json"), body));
        } else {
            request.method(method, null);
        }

        if (credentialsProvider.getPassword() != null) {
            request.addHeader("Authorization", getAuthorizationHeader());
        }

        if (userAgent != null) {
            request.addHeader("X-Signal-Agent", userAgent);
        }

        return okHttpClient.newCall(request.build()).execute();
    } catch (IOException e) {
        throw new PushNetworkException(e);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}

From source file:syncthing.api.SyncthingApiLongpollModule.java

License:Open Source License

@Provides
@SessionScope/*  w w  w.  jav a2 s. c  om*/
@Named("longpoll")
public SyncthingApi provideSyncthingApi(Gson gson, OkHttpClient okClient, SyncthingApiConfig config) {
    OkHttpClient client = okClient.clone();
    client.setConnectTimeout(LONGPOLL_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(LONGPOLL_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setSslSocketFactory(SyncthingSSLSocketFactory.create(config.getCACert()));
    client.setHostnameVerifier(new NullHostNameVerifier());
    client.interceptors().add(new SyncthingApiInterceptor(config));
    Retrofit.Builder b = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(client).baseUrl(config.getBaseUrl());
    if (BuildConfig.DEBUG) {
        b.validateEagerly();
    }
    return b.build().create(SyncthingApi.class);
}

From source file:syncthing.api.SyncthingApiModule.java

License:Open Source License

@Provides
@SessionScope/*  w w w. j  a v a 2  s . c  o  m*/
public SyncthingApi provideSyncthingApi(Gson gson, OkHttpClient okClient, SyncthingApiConfig config) {
    OkHttpClient client = okClient.clone();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setSslSocketFactory(SyncthingSSLSocketFactory.create(config.getCACert()));
    client.setHostnameVerifier(new NullHostNameVerifier());
    client.interceptors().add(new SyncthingApiInterceptor(config));
    Retrofit.Builder b = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(gson)).client(client).baseUrl(config.getBaseUrl());
    if (BuildConfig.DEBUG) {
        b.validateEagerly();
    }
    return b.build().create(SyncthingApi.class);
}