Example usage for com.squareup.okhttp OkHttpClient setSocketFactory

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

Introduction

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

Prototype

public OkHttpClient setSocketFactory(SocketFactory socketFactory) 

Source Link

Document

Sets the socket factory used to create connections.

Usage

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

License:Apache License

/**
 * Open an HTTP connection/*from  w  w w  . j av  a 2s  .  co  m*/
 *
 * 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:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java

License:Apache License

/**
 * @return a new http client/*from w ww  .  j  a  va 2s .  c  o m*/
 */
private OkHttpClient createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
    client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
    client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
    client.setFollowRedirects(connectorOptions.isFollowRedirects());
    client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
    client.setProxySelector(ProxySelector.getDefault());
    client.setCookieHandler(CookieHandler.getDefault());
    client.setCertificatePinner(CertificatePinner.DEFAULT);
    client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    client.setConnectionPool(ConnectionPool.getDefault());
    client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    client.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(client, Network.DEFAULT);

    return client;
}

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

License:Apache License

public static OkHttpClient createHttpClient(final Config config) {
    try {/*  ww  w  .  jav a 2s .  com*/
        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:org.bitcoinj.core.PeerGroup.java

License:Apache License

/**
 * <p>Creates a PeerGroup that accesses the network via the Tor network. The provided TorClient is used so you can
 * preconfigure it beforehand. It should not have been already started. You can just use "new TorClient()" if
 * you don't have any particular configuration requirements.</p>
 *
 * <p>If running on the Oracle JDK the unlimited strength jurisdiction checks will also be overridden,
 * as they no longer apply anyway and can cause startup failures due to the requirement for AES-256.</p>
 *
 * <p>The user does not need any additional software for this: it's all pure Java. As of April 2014 <b>this mode
 * is experimental</b>.</p>//from w ww  .  j a v a  2  s  .  c o m
 *
 * @params doDiscovery if true, DNS or HTTP peer discovery will be performed via Tor: this is almost always what you want.
 * @throws java.util.concurrent.TimeoutException if Tor fails to start within 20 seconds.
 */
public static PeerGroup newWithTor(Context context, @Nullable AbstractBlockChain chain, TorClient torClient,
        boolean doDiscovery) throws TimeoutException {
    checkNotNull(torClient);
    DRMWorkaround.maybeDisableExportControls();
    BlockingClientManager manager = new BlockingClientManager(torClient.getSocketFactory());
    final int CONNECT_TIMEOUT_MSEC = TOR_TIMEOUT_SECONDS * 1000;
    manager.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);
    PeerGroup result = new PeerGroup(context, chain, manager, torClient);
    result.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);

    if (doDiscovery) {
        NetworkParameters params = context.getParams();
        HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
        if (httpSeeds.length > 0) {
            // Use HTTP discovery when Tor is active and there is a Cartographer seed, for a much needed speed boost.
            OkHttpClient client = new OkHttpClient();
            client.setSocketFactory(torClient.getSocketFactory());
            result.addPeerDiscovery(new HttpDiscovery(params, httpSeeds[0], client));
        } else {
            result.addPeerDiscovery(new TorDiscovery(params, torClient));
        }
    }
    return result;
}

From source file:org.bitcoinj_extra.core.PeerGroup.java

License:Apache License

/**
 * <p>Creates a PeerGroup that accesses the network via the Tor network. The provided TorClient is used so you can
 * preconfigure it beforehand. It should not have been already started. You can just use "new TorClient()" if
 * you don't have any particular configuration requirements.</p>
 *
 * <p>If running on the Oracle JDK the unlimited strength jurisdiction checks will also be overridden,
 * as they no longer apply anyway and can cause startup failures due to the requirement for AES-256.</p>
 *
 * <p>The user does not need any additional software for this: it's all pure Java. As of April 2014 <b>this mode
 * is experimental</b>.</p>// w w  w .  j av a  2 s . c  o  m
 *
 * @param doDiscovery if true, DNS or HTTP peer discovery will be performed via Tor: this is almost always what you want.
 * @throws java.util.concurrent.TimeoutException if Tor fails to start within 20 seconds.
 */
public static PeerGroup newWithTor(Context context, @Nullable AbstractBlockChain chain, TorClient torClient,
        boolean doDiscovery) throws TimeoutException {
    checkNotNull(torClient);
    DRMWorkaround.maybeDisableExportControls();
    BlockingClientManager manager = new BlockingClientManager(torClient.getSocketFactory());
    final int CONNECT_TIMEOUT_MSEC = TOR_TIMEOUT_SECONDS * 1000;
    manager.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);
    PeerGroup result = new PeerGroup(context, chain, manager, torClient);
    result.setConnectTimeoutMillis(CONNECT_TIMEOUT_MSEC);

    if (doDiscovery) {
        NetworkParameters params = context.getParams();
        HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds();
        if (httpSeeds.length > 0) {
            // Use HTTP discovery when Tor is active and there is a Cartographer seed, for a much needed speed boost.
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.setSocketFactory(torClient.getSocketFactory());
            List<PeerDiscovery> discoveries = Lists.newArrayList();
            for (HttpDiscovery.Details httpSeed : httpSeeds)
                discoveries.add(new HttpDiscovery(params, httpSeed, httpClient));
            result.addPeerDiscovery(new MultiplexingDiscovery(params, discoveries));
        } else {
            result.addPeerDiscovery(new TorDiscovery(params, torClient));
        }
    }
    return result;
}

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 {/* w  ww. j  a v  a 2 s  .  c  o  m*/
        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  ww.j  a  v a  2 s . c  o 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.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 ww w  .  j a v a 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;
}