List of usage examples for com.squareup.okhttp OkHttpClient setConnectionPool
public OkHttpClient setConnectionPool(ConnectionPool connectionPool)
From source file:com.android.mms.service_alt.MmsHttpClient.java
License:Apache License
/** * Open an HTTP connection/* ww w .j a v a2 s . c o 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:com.facebook.buck.artifact_cache.ArtifactCaches.java
License:Apache License
private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig, BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) { URI uri = buckConfig.getHttpCacheUrl(); int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds(); boolean doStore = buckConfig.getHttpCacheReadMode(); final String host = buckConfig.getHostToReportToRemoteCacheServer(); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new Interceptor() { @Override// w ww. j av a 2s . c o m public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", host).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache("http", fetchClient, client, uri, doStore, projectFilesystem, buckEventBus); }
From source file:com.facebook.buck.cli.ArtifactCaches.java
License:Apache License
private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig, BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) { URL url = buckConfig.getHttpCacheUrl(); int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds(); boolean doStore = buckConfig.getHttpCacheReadMode(); final String host = buckConfig.getHostToReportToRemoteCacheServer(); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new Interceptor() { @Override/*w w w. ja v a2 s . co m*/ public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", host).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache("http", fetchClient, client, url, doStore, projectFilesystem, buckEventBus, Hashing.crc32()); }
From source file:com.facebook.buck.cli.BuckConfig.java
License:Apache License
private ArtifactCache createHttpArtifactCache() { URL url;// w ww .j a v a2 s. c o m try { url = new URL(getValue("cache", "http_url").or(DEFAULT_HTTP_URL)); } catch (MalformedURLException e) { throw new HumanReadableException(e, "Malformed [cache]http_url: %s", e.getMessage()); } int timeoutSeconds = Integer .parseInt(getValue("cache", "http_timeout_seconds").or(DEFAULT_HTTP_CACHE_TIMEOUT_SECONDS)); boolean doStore = readCacheMode("http_mode", DEFAULT_HTTP_CACHE_MODE); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); final String localhost = getLocalhost(); client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", localhost).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache(fetchClient, client, url, doStore, projectFilesystem, Hashing.crc32()); }
From source file:com.netflix.spinnaker.echo.config.Front50Config.java
License:Apache License
@Bean public OkHttpClient okHttpClient(OkHttpClientConfiguration okHttpClientConfig) { OkHttpClient cli = okHttpClientConfig.create(); cli.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs)); cli.setRetryOnConnectionFailure(retryOnConnectionFailure); return cli;/*from w ww . j a va 2s. c o m*/ }
From source file:com.netflix.spinnaker.halyard.config.config.v1.RetrofitConfig.java
License:Apache License
@Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) OkClient okClient() {/*from ww w . ja va2 s.co m*/ OkHttpClient client = okHttpClientConfig.create(); client.setConnectionPool(new ConnectionPool(maxIdleConnections, keepAliveDurationMs)); client.setRetryOnConnectionFailure(retryOnConnectionFailure); return new OkClient(client); }
From source file:com.spotify.apollo.http.client.OkHttpClientProvider.java
License:Apache License
@Override public OkHttpClient get() { final OkHttpClient client = new OkHttpClient(); //timeouts settings config.connectTimeoutMillis().ifPresent(millis -> client.setConnectTimeout(millis, TimeUnit.MILLISECONDS)); config.readTimeoutMillis().ifPresent(millis -> client.setReadTimeout(millis, TimeUnit.MILLISECONDS)); config.writeTimeoutMillis().ifPresent(millis -> client.setWriteTimeout(millis, TimeUnit.MILLISECONDS)); // connection pool settings client.setConnectionPool(new ConnectionPool( // defaults that come from com.squareup.okhttp.ConnectionPool config.maxIdleConnections().orElse(5), config.connectionKeepAliveDurationMillis().orElse(5 * 60 * 1000))); // async dispatcher settings config.maxAsyncRequests().ifPresent(max -> client.getDispatcher().setMaxRequests(max)); config.maxAsyncRequestsPerHost().ifPresent(max -> client.getDispatcher().setMaxRequestsPerHost(max)); closer.register(ExecutorServiceCloser.of(client.getDispatcher().getExecutorService())); return client; }
From source file:com.thanksmister.btcblue.data.api.ApiModule.java
License:Apache License
@Provides @Singleton/*from w w w. ja va 2 s . c o m*/ Client provideClient(OkHttpClient client) { client = new OkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout client.setConnectionPool(new ConnectionPool(0, 5 * 60 * 1000)); return new OkClient(client); }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client/* ww w. j a va 2s . com*/ */ 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 {//from w w w. j a va2 s .c o m 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); } }