List of usage examples for com.squareup.okhttp OkHttpClient setWriteTimeout
public void setWriteTimeout(long timeout, TimeUnit unit)
From source file:de.schildbach.wallet.data.DynamicFeeLoader.java
License:Open Source License
private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile, final String userAgent) { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(url);//from w w w. j a v a 2 s. c o m request.header("User-Agent", userAgent); if (targetFile.exists()) request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified()))); final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone(); httpClient.setConnectTimeout(5, TimeUnit.SECONDS); httpClient.setWriteTimeout(5, TimeUnit.SECONDS); httpClient.setReadTimeout(5, TimeUnit.SECONDS); final Call call = httpClient.newCall(request.build()); try { final Response response = call.execute(); final int status = response.code(); if (status == HttpURLConnection.HTTP_NOT_MODIFIED) { log.info("Dynamic fees not modified at {}, took {}", url, watch); } else if (status == HttpURLConnection.HTTP_OK) { final ResponseBody body = response.body(); final FileOutputStream os = new FileOutputStream(tempFile); Io.copy(body.byteStream(), os); os.close(); final Date lastModified = response.headers().getDate("Last-Modified"); if (lastModified != null) tempFile.setLastModified(lastModified.getTime()); body.close(); if (!tempFile.renameTo(targetFile)) throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile); watch.stop(); log.info("Dynamic fees fetched from {}, took {}", url, watch); } else { log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url); } } catch (final Exception x) { log.warn("Problem when fetching dynamic fees rates from " + url, x); } }
From source file:io.apiman.gateway.platforms.servlet.connectors.HttpConnectorFactory.java
License:Apache License
/** * @return a new http client/*from w w w. ja v a 2s. c om*/ */ 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: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)); }// w ww . j a v a 2 s.com 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 ww . ja va 2s . c om*/ 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 *//*ww w .j ava 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); }
From source file:net.callmeike.android.simplesync.net.NetModule.java
License:Apache License
static OkHttpClient createOkHttpClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, SECONDS); client.setReadTimeout(10, SECONDS);/*w w w. j av a 2s .c o m*/ client.setWriteTimeout(10, SECONDS); return client; }
From source file:org.eyeseetea.malariacare.network.NetworkUtils.java
License:Open Source License
/** * Pushes data to DHIS Server/*from w ww. ja va2 s. c om*/ * @param data */ public JSONObject pushData(JSONObject data) throws Exception { Response response = null; final String DHIS_URL = getDhisURL() + DHIS_PUSH_API; OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout client.setRetryOnConnectionFailure(false); // Cancel retry on failure BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); client.setAuthenticator(basicAuthenticator); Log.d(TAG, "Url" + DHIS_URL + ""); RequestBody body = RequestBody.create(JSON, data.toString()); Request request = new Request.Builder() .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL) .post(body).build(); response = client.newCall(request).execute(); if (!response.isSuccessful()) { Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string()); throw new IOException(response.message()); } return parseResponse(response.body().string()); }
From source file:org.eyeseetea.malariacare.network.NetworkUtils.java
License:Open Source License
/** * Call to DHIS Server/*from w ww . j a v a 2 s . c o m*/ * @param data * @param url */ public Response executeCall(JSONObject data, String url, String method) throws IOException { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); final String DHIS_URL = sharedPreferences.getString(applicationContext.getString(R.string.dhis_url), applicationContext.getString(R.string.login_info_dhis_default_server_url)) + url; OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient(); client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout client.setRetryOnConnectionFailure(false); // Cancel retry on failure BasicAuthenticator basicAuthenticator = new BasicAuthenticator(); client.setAuthenticator(basicAuthenticator); Request.Builder builder = new Request.Builder() .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL); switch (method) { case "POST": RequestBody postBody = RequestBody.create(JSON, data.toString()); builder.post(postBody); break; case "PUT": RequestBody putBody = RequestBody.create(JSON, data.toString()); builder.put(putBody); break; case "PATCH": RequestBody patchBody = RequestBody.create(JSON, data.toString()); builder.patch(patchBody); break; case "GET": builder.get(); break; } Request request = builder.build(); return client.newCall(request).execute(); }
From source file:org.graylog2.shared.bindings.providers.OkHttpClientProvider.java
License:Open Source License
@Override public OkHttpClient get() { final OkHttpClient client = new OkHttpClient(); client.setRetryOnConnectionFailure(true); client.setConnectTimeout(connectTimeout.getQuantity(), connectTimeout.getUnit()); client.setWriteTimeout(writeTimeout.getQuantity(), writeTimeout.getUnit()); client.setReadTimeout(readTimeout.getQuantity(), readTimeout.getUnit()); if (httpProxyUri != null) { final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyUri.getHost(), httpProxyUri.getPort())); client.setProxy(proxy);/*from w w w. ja v a 2 s . co m*/ } return client; }
From source file:org.openlmis.core.network.LMISRestManager.java
License:Open Source License
protected Client getSSLClient() { OkHttpClient httpClient = new OkHttpClient(); httpClient.setReadTimeout(1, TimeUnit.MINUTES); httpClient.setConnectTimeout(15, TimeUnit.SECONDS); httpClient.setWriteTimeout(30, TimeUnit.SECONDS); return new OkClient(httpClient); }