List of usage examples for com.squareup.okhttp OkHttpClient setConnectTimeout
public void setConnectTimeout(long timeout, TimeUnit unit)
From source file:com.uwetrottmann.getglue.Utils.java
License:Apache License
/** * Create an OkHttpClient with sensible timeouts for mobile connections. */// ww w .jav a 2 s. c o m public static OkHttpClient createOkHttpClient() { OkHttpClient okHttpClient = new OkHttpClient(); // set timeouts okHttpClient.setConnectTimeout(15 * 1000, TimeUnit.MILLISECONDS); okHttpClient.setReadTimeout(20 * 1000, TimeUnit.MILLISECONDS); return okHttpClient; }
From source file:com.vaporwarecorp.mirror.app.MirrorApplication.java
License:Apache License
private void initializeGlide() { Cache cache = new Cache(new File(getCacheDir(), "http"), 25 * 1024 * 1024); OkHttpClient mOkHttpClient = new OkHttpClient(); mOkHttpClient.setCache(cache);//from w w w .j a v a 2 s .co m mOkHttpClient.setConnectTimeout(10, SECONDS); mOkHttpClient.setReadTimeout(10, SECONDS); mOkHttpClient.setWriteTimeout(10, SECONDS); Glide.get(getApplicationContext()).register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(mOkHttpClient)); }
From source file:com.wialon.remote.OkSdkHttpClient.java
License:Apache License
public OkHttpClient getHttpClient(int timeout) { if ((timeout == 0 || timeout == DEFAULT_SOCKET_TIMEOUT) && defaultClient != null) return defaultClient; else {//from w w w . ja v a2s . c om OkHttpClient client = new OkHttpClient(); timeout = timeout == 0 ? DEFAULT_SOCKET_TIMEOUT : timeout; client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); return client; } }
From source file:com.windigo.http.client.OkClient.java
License:Apache License
private static OkHttpClient generateDefaultOkHttp() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(GlobalSettings.CONNNECTION_TIMEOUT, TimeUnit.MILLISECONDS); client.setReadTimeout(GlobalSettings.CONNECTION_READ_TIMEOUT, TimeUnit.MILLISECONDS); return client; }
From source file:com.yandex.disk.rest.OkHttpClientFactory.java
License:Apache License
public static OkHttpClient makeClient() { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setWriteTimeout(WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); client.setFollowSslRedirects(true);/*from www .j a v a 2 s . c o m*/ client.setFollowRedirects(true); return client; }
From source file:com.ydh.gva.util.net.volley.toolbox.OkHttpStack.java
License:Open Source 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); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); okHttpRequestBuilder.addHeader("clientos", "101"); okHttpRequestBuilder.addHeader("osversion", SystemVal.sdk + ""); okHttpRequestBuilder.addHeader("clientphone", SystemVal.model + ""); okHttpRequestBuilder.addHeader("weiLeversion", SystemVal.versionCode + ""); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from ww w.ja v a 2 s.co 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:com.yetanotherdevblog.rottentomatoes.api.RottenTomatoes.java
License:Apache License
/** * Return the current {@link retrofit.RestAdapter} instance. If none exists (first call, API key changed), * builds a new one./*ww w.ja v a 2 s .com*/ * <p> * When building, sets the endpoint, a custom converter ({@link RottenTomatoesHelper#getGsonBuilder()}) * and a {@link retrofit.RequestInterceptor} which adds the API key as query param. */ protected RestAdapter getRestAdapter() { if (restAdapter == null) { RestAdapter.Builder builder = newRestAdapterBuilder(); builder.setEndpoint(API_URL); builder.setConverter(new GsonConverter(RottenTomatoesHelper.getGsonBuilder().create())); builder.setRequestInterceptor(new RequestInterceptor() { public void intercept(RequestFacade requestFacade) { requestFacade.addQueryParam(PARAM_API_KEY, apiKey); } }); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, TimeUnit.SECONDS); client.setReadTimeout(10, TimeUnit.SECONDS); client.setWriteTimeout(10, TimeUnit.SECONDS); builder.setClient(new OkClient(client)); if (isDebug) { builder.setLogLevel(RestAdapter.LogLevel.FULL); } restAdapter = builder.build(); } return restAdapter; }
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 ww . j av a2s.c om 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:fr.eo.api.ApiErrorTest.java
License:Open Source License
@Ignore @Test(expected = RetrofitError.class) public void testTimeout() throws FileNotFoundException { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(1, TimeUnit.MILLISECONDS); client.setReadTimeout(1, TimeUnit.MILLISECONDS); AccountService accountService = new Manager().setClient(new OkClient(client)) .setErrorHandler(new NetworkErrorHandler() { @Override/*from w ww .j a va 2s. c o m*/ public void onNoInternetError(RetrofitError cause) { System.err.println("No internet connection !"); } @Override public void onTimeOutError(RetrofitError cause) { assertTrue(true); } }).accountService(); TestCredential testCredential = getCredential(); accountService.apiKeyInfo(testCredential.keyID, testCredential.vCode); fail("No error occured !"); }
From source file:info.curtbinder.reefangel.service.ControllerTask.java
License:Creative Commons License
public void run() { // Communicate with controller // clear out the error code on run rapp.clearErrorCode();//from w ww . j ava 2 s .c om Response response = null; boolean fInterrupted = false; broadcastUpdateStatus(R.string.statusStart); try { URL url = new URL(host.toString()); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(host.getConnectTimeout(), TimeUnit.MILLISECONDS); client.setReadTimeout(host.getReadTimeout(), TimeUnit.MILLISECONDS); Request.Builder builder = new Request.Builder(); builder.url(url); if (host.isDeviceAuthenticationEnabled()) { String creds = Credentials.basic(host.getWifiUsername(), host.getWifiPassword()); builder.header("Authorization", creds); } Request req = builder.build(); broadcastUpdateStatus(R.string.statusConnect); response = client.newCall(req).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); if (Thread.interrupted()) throw new InterruptedException(); } catch (MalformedURLException e) { rapp.error(1, e, "MalformedURLException"); } catch (SocketTimeoutException e) { rapp.error(5, e, "SocketTimeoutException"); } catch (ConnectException e) { rapp.error(3, e, "ConnectException"); } catch (UnknownHostException e) { String msg = "Unknown Host: " + host.toString(); UnknownHostException ue = new UnknownHostException(msg); rapp.error(4, ue, "UnknownHostException"); } catch (EOFException e) { EOFException eof = new EOFException(rapp.getString(R.string.errorAuthentication)); rapp.error(3, eof, "EOFException"); } catch (IOException e) { rapp.error(3, e, "IOException"); } catch (InterruptedException e) { fInterrupted = true; } processResponse(response, fInterrupted); }