Java Code Examples for com.squareup.okhttp.OkHttpClient#setSslSocketFactory()

The following examples show how to use com.squareup.okhttp.OkHttpClient#setSslSocketFactory() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestVolley.java    From RestVolley with Apache License 2.0 6 votes vote down vote up
/**
 * create a new http engine with tag that contains OkHttpClient and RequestQueue.
 * <br>
 * <br>
 * if the http engine with the special tag exists, return the existing http engine, otherwise create a new http engine and return.
 * @param context Context.
 * @param engineTag http engine Tag related to the http engine.
 * @return HttpEngine.
 */
public static RequestEngine newRequestEngine(Context context, String engineTag, boolean isStreamBased) {
    RequestEngine requestEngine = sRequestEngineMap.get(engineTag);
    if (requestEngine == null) {
        OkHttpClient okHttpClient = new OkHttpClient();

        okHttpClient.setConnectTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setWriteTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setSslSocketFactory(CertificateUtils.getDefaultSSLSocketFactory());
        okHttpClient.setHostnameVerifier(CertificateUtils.ALLOW_ALL_HOSTNAME_VERIFIER);

        RequestQueue requestQueue = newRequestQueue(context.getApplicationContext(), new OkHttpStack(okHttpClient), DEF_THREAD_POOL_SIZE, isStreamBased);
        requestQueue.start();

        requestEngine = new RequestEngine(requestQueue, okHttpClient);

        sRequestEngineMap.put(engineTag, requestEngine);
    }

    return requestEngine;
}
 
Example 2
Source File: OkHttpClientExample.java    From http2-examples with Apache License 2.0 6 votes vote down vote up
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, TRUST_ALL_CERTS, 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((hostname, session) -> true);

        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: LoboBrowser.java    From LoboBrowser with MIT License 6 votes vote down vote up
/**
 * Initializes the global URLStreamHandlerFactory.
 * <p>
 * This method is invoked by {@link #init(boolean, boolean)}.
 */
public static void initProtocols(final SSLSocketFactory sslSocketFactory) {
  // Configure URL protocol handlers
  final StreamHandlerFactory factory = StreamHandlerFactory.getInstance();
  URL.setURLStreamHandlerFactory(factory);
  final OkHttpClient okHttpClient = new OkHttpClient();

  final ArrayList<Protocol> protocolList = new ArrayList<>(2);
  protocolList.add(Protocol.HTTP_1_1);
  protocolList.add(Protocol.HTTP_2);
  okHttpClient.setProtocols(protocolList);

  okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS);

  // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
  okHttpClient.setSslSocketFactory(sslSocketFactory);
  okHttpClient.setFollowRedirects(false);
  okHttpClient.setFollowSslRedirects(false);
  factory.addFactory(new OkUrlFactory(okHttpClient));
  factory.addFactory(new LocalStreamHandlerFactory());
}
 
Example 4
Source File: OkHttpClientFactory.java    From Auth0.Android with MIT License 5 votes vote down vote up
/**
 * Enable TLS 1.2 on the OkHttpClient on API 16-21, which is supported but not enabled by default.
 *
 * @link https://github.com/square/okhttp/issues/2372
 * @see TLS12SocketFactory
 */
private void enforceTls12(OkHttpClient client) {
    // No need to modify client as TLS 1.2 is enabled by default on API21+
    // Lollipop is included because some Samsung devices face the same problem on API 21.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN
            || Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        return;
    }
    try {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, null, null);
        client.setSslSocketFactory(new TLS12SocketFactory(sc.getSocketFactory()));

        ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .build();

        List<ConnectionSpec> specs = new ArrayList<>();
        specs.add(cs);
        specs.add(ConnectionSpec.COMPATIBLE_TLS);
        specs.add(ConnectionSpec.CLEARTEXT);

        client.setConnectionSpecs(specs);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        Log.e(TAG, "Error while setting TLS 1.2", e);
    }
}
 
Example 5
Source File: TapchatModule.java    From tapchat-android with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton public OkHttpClient provideOkHttp(SSLSocketFactory sslSocketFactory,
        HostnameVerifier hostnameVerifier) {

    try {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setCache(new Cache(mAppContext.getCacheDir(), MAX_CACHE_SIZE));
        okHttpClient.setHostnameVerifier(hostnameVerifier);
        okHttpClient.setSslSocketFactory(sslSocketFactory);
        return okHttpClient;
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 6
Source File: NetworkUtils.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static HttpURLConnection getHttpURLConnection(final URL url, final Cache cache, final SSLSocketFactory sslSocketFactory) {
    OkHttpClient client = new OkHttpClient();
    if (cache != null) {
        client.setCache(cache);
    }
    if (sslSocketFactory != null) {
        client.setSslSocketFactory(sslSocketFactory);
    }
    HttpURLConnection connection = new OkUrlFactory(client).open(url);
    connection.setRequestProperty("User-Agent", MapboxUtils.getUserAgent());
    return connection;
}
 
Example 7
Source File: OkHttpRequestor.java    From dropbox-sdk-java with MIT License 5 votes vote down vote up
/**
 * Returns an {@code OkHttpClient} instance with the default settings for this SDK.
 */
public static OkHttpClient defaultOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    // enables certificate pinning
    client.setSslSocketFactory(SSLConfig.getSSLSocketFactory());
    return client;
}
 
Example 8
Source File: InvokeHTTP.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@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);
    }

    // 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);
}
 
Example 9
Source File: WebSocketClientGenerator.java    From hawkular-android-client with Apache License 2.0 4 votes vote down vote up
public WebSocketClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    if(configuration.getConnectTimeoutSeconds()!=-1){
        httpClient.setConnectTimeout(configuration.getConnectTimeoutSeconds(), TimeUnit.SECONDS);
    }

    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;
}