List of usage examples for com.squareup.okhttp OkHttpClient setConnectTimeout
public void setConnectTimeout(long timeout, TimeUnit unit)
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client// w w w.jav a2 s . co 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.apptik.comm.jus.okhttp.OkHttpStack.java
License:Apache License
@Override public NetworkResponse performRequest(Request<?> request, Headers additionalHeaders, ByteArrayPool byteArrayPool) throws IOException { //clone to be able to set timeouts per call OkHttpClient client = this.client.clone(); client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit.MILLISECONDS); com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder() .url(request.getUrlString()).headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders)) .tag(request.getTag()).method(request.getMethod(), JusOk.okBody(request.getNetworkRequest())) .build();/*from w ww .j av a 2s . com*/ long requestStart = System.nanoTime(); Response response = client.newCall(okRequest).execute(); byte[] data = null; if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) { data = getContentBytes(response.body().source(), byteArrayPool, (int) response.body().contentLength()); } else { // Add 0 byte response as a way of honestly representing a // no-content request. data = new byte[0]; } return new NetworkResponse.Builder().setHeaders(JusOk.jusHeaders(response.headers())) .setStatusCode(response.code()).setBody(data).setNetworkTimeNs(System.nanoTime() - requestStart) .build(); }
From source file:io.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {/*from ww w. ja va 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 {/*from w w w . ja v a 2s . c o 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); } }
From source file:io.macgyver.plugin.elb.a10.A10ClientImpl.java
License:Apache License
protected OkHttpClient getClient() { // not guaranteed to be singleton, but close enough if (clientReference.get() == null) { OkHttpClient c = new OkHttpClient(); c.setConnectTimeout(20, TimeUnit.SECONDS); c.setHostnameVerifier(withoutHostnameVerification()); c.setSslSocketFactory(withoutCertificateValidation().getSocketFactory()); c.setConnectionSpecs(getA10CompatibleConnectionSpecs()); c.interceptors().add(LoggingInterceptor.create(A10ClientImpl.class)); clientReference.set(c);/*from w w w. ja va 2 s. c om*/ } return clientReference.get(); }
From source file:io.macgyver.plugin.pagerduty.PagerDutyClientImpl.java
License:Apache License
protected OkHttpClient newEventClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, TimeUnit.SECONDS); if (!getCertificateValidationEnabled()) { client = client.setHostnameVerifier(SslTrust.withoutHostnameVerification()); client = client.setSslSocketFactory(SslTrust.withoutCertificateValidation().getSocketFactory()); }// www .ja v a 2s . com return client; }
From source file:io.takari.aether.okhttp.OkHttpAetherClient.java
License:Open Source License
public OkHttpAetherClient(AetherClientConfig config) { this.config = config; // headers are modified during http auth handshake // make a copy to avoid cross-talk among client instances headers = new HashMap<String, String>(); if (config.getHeaders() != null) { headers.putAll(config.getHeaders()); }//from ww w.ja v a2 s . c o m // // If the User-Agent has been overriden in the headers then we will use that // if (!headers.containsKey("User-Agent")) { headers.put("User-Agent", config.getUserAgent()); } OkHttpClient httpClient = new OkHttpClient(); httpClient.setProxy(getProxy(config.getProxy())); httpClient.setHostnameVerifier(OkHostnameVerifier.INSTANCE); httpClient.setAuthenticator(NOAUTH); // see #authenticate below httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); httpClient.setSslSocketFactory(config.getSslSocketFactory()); this.httpClient = httpClient; }
From source file:library.util.OkHttpStack.java
License:Apache License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); int timeoutMs = request.getTimeoutMs(); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); Builder okHttpRequestBuilder = new Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from www . j a v a2s. c o m*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:me.hoangchunghien.popularmovies.data.api.ApiModule.java
License:Apache License
@Provides @Singleton//from w w w . j a va 2 s. c o m OkHttpClient provideOkHttpClient(@ForApplication Context app) { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, SECONDS); client.setReadTimeout(10, SECONDS); client.setWriteTimeout(10, SECONDS); // Install an HTTP cache in the application cache directory. File cacheDir = new File(app.getCacheDir(), "http"); Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE); client.setCache(cache); return client; }
From source file:meteor.operations.Meteor.java
License:Apache License
/** * Opens a connection to the server over websocket * * @param isReconnect whether this is a re-connect attempt or not *//* www.j a v a 2 s . co m*/ public void openConnection(final boolean isReconnect) { if (isReconnect) { if (isConnected()) { connect(mSessionID); return; } } OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MINUTES); client.setReadTimeout(1, TimeUnit.MINUTES); client.setWriteTimeout(1, TimeUnit.MINUTES); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); client.networkInterceptors().add(loggingInterceptor); Request request = new Request.Builder().url(mServerUri).build(); WebSocketCall.create(client, request).enqueue(mWebSocketObserver); }