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:ca.mymenuapp.data.DebugDataModule.java

License:Open Source License

@Provides
@Singleton//  w  ww . j a  v a  2 s. c om
OkHttpClient provideOkHttpClient(@ForApplication Context applicationContext) {
    OkHttpClient client = DataModule.createOkHttpClient(applicationContext);
    client.setSslSocketFactory(createBadSslSocketFactory());
    return client;
}

From source file:com.android.mms.service_alt.MmsHttpClient.java

License:Apache License

/**
 * Open an HTTP connection/*from  ww w .j  a  va  2  s. com*/
 *
 * TODO: The following code is borrowed from android.net.Network.openConnection
 * Once that method supports proxy, we should use that instead
 * Also we should remove the associated HostResolver and ConnectionPool from
 * MmsNetworkManager
 *
 * @param url The URL to connect to
 * @param proxy The proxy to use
 * @return The opened HttpURLConnection
 * @throws MalformedURLException If URL is malformed
 */
private HttpURLConnection openConnection(URL url, final Proxy proxy) throws MalformedURLException {
    final String protocol = url.getProtocol();
    OkHttpClient okHttpClient;
    if (protocol.equals("http")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setFollowRedirects(false);
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (proxy != null) {
                    return Arrays.asList(proxy);
                } else {
                    return new ArrayList<Proxy>();
                }
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        okHttpClient.setSocketFactory(SocketFactory.getDefault());
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

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

        return new HttpURLConnectionImpl(url, okHttpClient);
    } else if (protocol.equals("https")) {
        okHttpClient = new OkHttpClient();
        okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
        HostnameVerifier verifier = HttpsURLConnection.getDefaultHostnameVerifier();
        okHttpClient.setHostnameVerifier(verifier);
        okHttpClient.setSslSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
        okHttpClient.setProxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress address, IOException failure) {

            }
        });
        okHttpClient.setAuthenticator(new com.squareup.okhttp.Authenticator() {
            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                return null;
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
        okHttpClient.setConnectionSpecs(Arrays.asList(ConnectionSpec.CLEARTEXT));
        okHttpClient.setConnectionPool(new ConnectionPool(3, 60000));
        Internal.instance.setNetwork(okHttpClient, mHostResolver);

        return new HttpsURLConnectionImpl(url, okHttpClient);
    } else {
        throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol);
    }
}

From source file:com.android.volley.toolbox.Volley.java

License:Apache License

/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 *///w  w  w .  j a  v a 2 s .  c o  m
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    if (stack == null) {
        stack = new OkHttpStack();
        OkHttpClient client = ((OkHttpStack) stack).getClient();

        SSLContext sslContext;
        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());
        URL.setURLStreamHandlerFactory(client);
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}

From source file:com.arbalest.http.ArbalestClientFactory.java

License:Open Source License

private OkHttpClient createOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    SSLContext sslContext;/*from w  w  w. j a va 2s  . co m*/
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
    } catch (GeneralSecurityException e) {
        throw new AssertionError(e);
    }
    client.setSslSocketFactory(sslContext.getSocketFactory());
    return client;
}

From source file:com.brq.wallet.bitid.BitIdAuthenticator.java

License:Microsoft Reference Source License

private OkHttpClient getOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    if (!enforceSslCorrectness) {
        //user explicitly agreed to not check certificates
        client.setSslSocketFactory(SslUtils.SSL_SOCKET_FACTORY_ACCEPT_ALL);
        client.setHostnameVerifier(SslUtils.HOST_NAME_VERIFIER_ACCEPT_ALL);
    }// w ww . j ava2 s  .co m
    client.setConnectTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    return client;
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private static OkHttpClient buildDefaultClient() {
    OkHttpClient c = new OkHttpClient();

    c.setFollowRedirects(true);/*from   ww w. j ava 2s.  c o m*/
    c.setFollowSslRedirects(true);
    c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setHostnameVerifier(buildHostnameVerifier());
    c.setSslSocketFactory(buildSSLSocketFactory());
    c.interceptors().add(new GzipInterceptor());

    return c;
}

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

License:Apache License

/**
 * Returns a OkHttpClient that ignores SSL cert errors
 * @return//from  ww w.j av a2s.c o  m
 */
private static OkHttpClient getUnsafeOkHttpClient() {
    try {
        // 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:com.gst.infrastructure.hooks.processor.ProcessorHelper.java

License:Apache License

@SuppressWarnings("null")
public static OkHttpClient configureClient(final OkHttpClient client) {
    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override/*from  w ww  .j  a va  2 s  . 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 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:com.lobobrowser.LoboBrowser.java

License:Open Source License

/**
 * Initializes the global URLStreamHandlerFactory.
 * <p>/*from www .  j  a  va 2s.  c  o  m*/
 * This method is invoked by {@link #init(boolean, boolean)}.
 */
public static void initProtocols(final SSLSocketFactory sslSocketFactory) {
    // Configure URL protocol handlers
    final PlatformStreamHandlerFactory factory = PlatformStreamHandlerFactory.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());
}

From source file:com.mifos.services.API.java

private OkHttpClient getUnsafeOkHttpClient() {
    try {/*from   w  ww  .jav a  2 s  . co  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);
    }
}