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:com.netflix.spinnaker.clouddriver.docker.registry.api.v2.client.DefaultDockerOkClientProvider.java

License:Apache License

@Override
public OkClient provide(String address, long timeoutMs, boolean insecure) {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    if (insecure) {
        SSLContext sslContext;//from  w ww. j  ava2 s  .  c om
        try {
            sslContext = SSLContext.getInstance("SSL");
            TrustManager[] trustManagers = { new TrustAllX509TrustManager() };
            sslContext.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new IllegalStateException("Failed configuring insecure SslSocketFactory", e);
        }
        client.setSslSocketFactory(sslContext.getSocketFactory());
    }

    return new OkClient(client);
}

From source file:com.netflix.spinnaker.igor.concourse.client.OkHttpClientBuilder.java

License:Apache License

public static OkHttpClient retryingClient(Supplier<Token> refreshToken) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(chain -> OkHttpClientBuilder.createRetryInterceptor(chain, refreshToken));
    okHttpClient.setHostnameVerifier((s, sslSession) -> true);
    okHttpClient.setSslSocketFactory(getSslContext().getSocketFactory());
    okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(15, TimeUnit.SECONDS);
    return okHttpClient;
}

From source file:com.open.taogubaweex.adapter.DefaultWebSocketAdapter.java

License:Apache License

@Override
public void connect(String url, @Nullable String protocol, EventListener listener) {
    this.eventListener = listener;
    OkHttpClient okHttpClient = new OkHttpClient();

    Request.Builder builder = new Request.Builder();

    if (protocol != null) {
        builder.addHeader(HEADER_SEC_WEBSOCKET_PROTOCOL, protocol);
    }//from  w w w  . ja va 2s  .co m
    url = url + "?token=" + URLEncoder.encode("android_1262670&B05016B999132BC0C7C69297B1748CB6");
    builder.url(url);

    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {

            //                public void checkClientTrusted(X509Certificate[] certs, String authType) {
            //                    System.out.println("checkClientTrusted1");
            //                }

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkClientTrusted2");
            }

            //                public void checkServerTrusted(X509Certificate[] certs,
            //                                               String authType) {
            //                    System.out.println("checkServerTrusted1");
            //                }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {
                System.out.println("checkServerTrusted2");
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLSocketFactory factory = sslContext.getSocketFactory();
    okHttpClient.setSslSocketFactory(factory);

    WebSocketCall.create(okHttpClient, builder.build()).enqueue(new WebSocketListener() {
        @Override
        public void onOpen(WebSocket webSocket, Request request, Response response) throws IOException {
            ws = webSocket;
            eventListener.onOpen();
        }

        @Override
        public void onMessage(BufferedSource payload, WebSocket.PayloadType type) throws IOException {
            eventListener.onMessage(payload.readUtf8());
            payload.close();
        }

        @Override
        public void onPong(Buffer payload) {

        }

        @Override
        public void onClose(int code, String reason) {
            eventListener.onClose(code, reason, true);
        }

        @Override
        public void onFailure(IOException e) {
            e.printStackTrace();
            if (e instanceof EOFException) {
                eventListener.onClose(WebSocketCloseCodes.CLOSE_NORMAL.getCode(),
                        WebSocketCloseCodes.CLOSE_NORMAL.name(), true);
            } else {
                eventListener.onError(e.getMessage());
            }
        }
    });
}

From source file:com.startechup.tools.http.SSLHttpStack.java

License:Apache License

public SSLHttpStack(InputStream inputClientKey, InputStream inputTrustKey) {
    mInputClientKey = inputClientKey;/*w  ww  . ja va 2  s. c  o m*/
    mInputTrustKey = inputTrustKey;

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setSslSocketFactory(createSSLContext().getSocketFactory());
    okHttpClient.setHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            // I have to override this method or our mutual SSL authentication will fail.
            return true;
        }
    });

    mOkUrlFactory = new OkUrlFactory(okHttpClient);
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.OkHttpStack.java

License:Apache License

public OkHttpStack(OkHttpClient client, CookieManager cookieManager) {
    if (client == null) {
        throw new NullPointerException("Client must not be null.");
    }/*w  ww.j  a  va  2 s . c o m*/

    if (ConfigDataProvider.DEBUG && ConfigDataProvider.SSL_ALL_PASS) {
        // 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;
            }
        } };
        try {
            // 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();

            client.setSslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // client.setSslSocketFactory(fake);
        client.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }
    this.client = client;
    this.client.setCookieHandler(cookieManager);

    //      CookieManager cookieManager = new CookieManager();
    //      cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    //      this.client.setCookieHandler(cookieManager);

    //      this.client.setCookieHandler(new CookieManager(
    //                new PersistentCookieStore(context),
    //                CookiePolicy.ACCEPT_ALL));
    factory = new OkUrlFactory(client);
}

From source file:com.uwetrottmann.androidutils.AndroidUtils.java

License:Apache License

/**
 * Create an OkHttpClient with its own private SSL context. Avoids libssl crash because other
 * libraries do not expect the global SSL context to be changed. Also see
 * https://github.com/square/okhttp/issues/184.
 *//* ww  w .j av  a2s  .co m*/
public static OkHttpClient createOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();

    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.
    }
    okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

    return okHttpClient;
}

From source file:com.xjeffrose.xio2.http.server.ServerTest.java

License:Apache License

private OkHttpClient getUnsafeOkHttpClient() {
    try {//from  w  ww.  j  a v a2s .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("TLSv1.2");
        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:es.bsc.vmmclient.rest.VmmRestClient.java

License:Open Source License

private static OkHttpClient getUnsafeOkHttpClient() {
    try {//from   w  w  w. ja  v a2  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 new java.security.cert.X509Certificate[] {};
            }
        } };

        // 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:io.fabric8.docker.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {//  w  ww  . j  ava  2s  .  c om
        OkHttpClient httpClient = new OkHttpClient();

        httpClient.setConnectionPool(ConnectionPool.getDefault());
        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        if (usesUnixSocket(config)) {
            URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME));
            httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile()));
            config.setDockerUrl(UNIX_FAKE_URL);
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new DockerClientException("Invalid proxy server configuration", e);
            }
        }

        return httpClient;
    } catch (Exception e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {// w  w w  .  java  2 s.  co m
        OkHttpClient httpClient = new OkHttpClient();

        // Follow any redirects
        httpClient.setFollowRedirects(true);
        httpClient.setFollowSslRedirects(true);

        if (config.isTrustCerts()) {
            httpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        TrustManager[] trustManagers = SSLUtils.trustManagers(config);
        KeyManager[] keyManagers = SSLUtils.keyManagers(config);

        if (keyManagers != null || trustManagers != null || config.isTrustCerts()) {
            try {
                SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts());
                httpClient.setSslSocketFactory(sslContext.getSocketFactory());
            } catch (GeneralSecurityException e) {
                throw new AssertionError(); // The system has no TLS. Just give up.
            }
        }

        if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) {
            httpClient.setAuthenticator(new Authenticator() {

                @Override
                public Request authenticate(Proxy proxy, Response response) throws IOException {
                    List<Challenge> challenges = response.challenges();
                    Request request = response.request();
                    HttpUrl url = request.httpUrl();
                    for (int i = 0, size = challenges.size(); i < size; i++) {
                        Challenge challenge = challenges.get(i);
                        if (!"Basic".equalsIgnoreCase(challenge.getScheme()))
                            continue;

                        String credential = Credentials.basic(config.getUsername(), config.getPassword());
                        return request.newBuilder().header("Authorization", credential).build();
                    }
                    return null;
                }

                @Override
                public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                    return null;
                }
            });
        } else if (config.getOauthToken() != null) {
            httpClient.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request authReq = chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + config.getOauthToken()).build();
                    return chain.proceed(authReq);
                }
            });
        }

        Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class);
        if (reqLogger.isTraceEnabled()) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.networkInterceptors().add(loggingInterceptor);
        }

        if (config.getConnectionTimeout() > 0) {
            httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
        }

        if (config.getRequestTimeout() > 0) {
            httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
        }

        // Only check proxy if it's a full URL with protocol
        if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX)
                || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) {
            try {
                URL proxyUrl = getProxyUrl(config);
                if (proxyUrl != null) {
                    httpClient.setProxy(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));
                }
            } catch (MalformedURLException e) {
                throw new KubernetesClientException("Invalid proxy server configuration", e);
            }
        }

        if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent())
                            .build();
                    return chain.proceed(agent);
                }
            });
        }

        return httpClient;
    } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
    }
}