List of usage examples for com.squareup.okhttp OkHttpClient setConnectTimeout
public void setConnectTimeout(long timeout, TimeUnit unit)
From source file:com.av.remusic.lastfmapi.RestServiceFactory.java
License:Open Source License
public static <T> T create(final Context context, String baseUrl, Class<T> clazz) { final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setCache(new Cache(context.getApplicationContext().getCacheDir(), CACHE_SIZE)); okHttpClient.setConnectTimeout(40, TimeUnit.SECONDS); RequestInterceptor interceptor = new RequestInterceptor() { @Override// w w w .java 2 s . c o m public void intercept(RequestFacade request) { //7-days cache request.addHeader("Cache-Control", String.format("max-age=%d,max-stale=%d", Integer.valueOf(60 * 60 * 24 * 7), Integer.valueOf(31536000))); request.addHeader("Connection", "keep-alive"); } }; RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(baseUrl) .setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient)); return builder.build().create(clazz); }
From source file:com.brq.wallet.bitid.BitIdAuthenticator.java
License:Microsoft Reference Source License
private OkHttpClient getOkHttpClient() { OkHttpClient client = new OkHttpClient(); if (!enforceSslCorrectness) { //user explicitly agreed to not check certificates client.setSslSocketFactory(SslUtils.SSL_SOCKET_FACTORY_ACCEPT_ALL); client.setHostnameVerifier(SslUtils.HOST_NAME_VERIFIER_ACCEPT_ALL); }/*ww w. j a va 2 s . c o m*/ client.setConnectTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS); client.setReadTimeout(Constants.SHORT_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS); return client; }
From source file:com.brq.wallet.external.glidera.api.GlideraService.java
private GlideraService(@NonNull final NetworkParameters networkParameters) { Preconditions.checkNotNull(networkParameters); this.networkParameters = networkParameters; this.baseUrl = getBaseUrl(networkParameters); if (networkParameters.isTestnet()) { clientId = TESTNET_CLIENT_ID;/*from w w w .j a va2s . co m*/ } else { clientId = MAINNET_CLIENT_ID; } /** * The Sha256 HMAC hash of the message. Use the secret matching the access_key to hash the message. * The message is the concatenation of the X-ACCESS-NONCE + URI of the request + message body JSON. * The final X-ACCESS-SIGNATURE is the HmacSha256 of the UTF-8 encoding of the message as a Hex encoded string */ final Interceptor apiCredentialInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (_oAuth1Response != null) { Request.Builder requestBuilder = request.newBuilder(); synchronized (_nonce) { final String nonce = _nonce.getNonceString(); final String uri = request.urlString(); String message = nonce + uri; if (request.body() != null && request.body().contentLength() > 0) { Buffer bodyBuffer = new Buffer(); request.body().writeTo(bodyBuffer); byte[] bodyBytes = bodyBuffer.readByteArray(); String body = new String(bodyBytes, Charsets.UTF_8); message += body; } final byte[] messageBytes = message.getBytes(Charsets.UTF_8); final byte[] secretBytes = _oAuth1Response.getSecret().getBytes(Charsets.UTF_8); final byte[] signatureBytes = Hmac.hmacSha256(secretBytes, messageBytes); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Hex.encode(signatureBytes, stream); final String signature = stream.toString(); request = requestBuilder.header(HEADER_ACCESS_KEY, _oAuth1Response.getAccess_key()) .header(HEADER_ACCESS_NONCE, nonce).header(HEADER_ACCESS_SIGNATURE, signature) .build(); } } return chain.proceed(request); } }; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15000, TimeUnit.MILLISECONDS); client.setReadTimeout(15000, TimeUnit.MILLISECONDS); client.networkInterceptors().add(apiCredentialInterceptor); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.); objectMapper.registerModule(new WapiJsonModule()); /* We should always add client_id to the header */ RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { requestFacade.addHeader(HEADER_CLIENT_ID, clientId); } }; /* Create the json adapter */ RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + "/api/" + API_VERSION + "/") //.setLogLevel(RestAdapter.LogLevel.FULL) .setLogLevel(RestAdapter.LogLevel.BASIC).setLog(new AndroidLog("Glidera")) .setConverter(new JacksonConverter(objectMapper)).setClient(new NullBodyAwareOkClient(client)) .setRequestInterceptor(requestInterceptor).build(); glideraApi = adapter.create(GlideraApi.class); }
From source file:com.burhan.udacity.popularmovies.data.DataModule.java
License:Apache License
static OkHttpClient createOkHttpClient(Application app) { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, SECONDS); client.setReadTimeout(10, SECONDS);/* w w w.j av a 2 s. c o m*/ 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:com.cuddlesoft.norilib.service.ServiceTypeDetectionService.java
@Override protected void onHandleIntent(Intent intent) { // Extract SearchClient.Settings from the received Intent. final Uri uri = Uri.parse(intent.getStringExtra(ENDPOINT_URL)); final Intent broadcastIntent = new Intent(ACTION_DONE); if (uri.getHost() == null || uri.getScheme() == null) { // The URL supplied is invalid. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_INVALID_URL)); return;// ww w .j av a 2s . c o m } // Create the HTTP client. final OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.setConnectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); okHttpClient.setReadTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS); // Iterate over supported URI schemes for given URL. for (String uriScheme : (TLS_SUPPORT.contains(uri.getHost()) ? URI_SCHEMES_PREFER_SSL : URI_SCHEMES)) { String baseUri = uriScheme + uri.getHost(); // Iterate over each endpoint path. for (Map.Entry<SearchClient.Settings.APIType, String> entry : API_ENDPOINT_PATHS.entrySet()) { // Create a HTTP request object. final Request request = new Request.Builder().url(baseUri + entry.getValue()).build(); try { // Fetch response. final Response response = okHttpClient.newCall(request).execute(); // Make sure the response code was OK and that the HTTP client wasn't redirected along the way. if (response.code() == HttpStatus.SC_OK && response.priorResponse() == null) { // Found an API endpoint. broadcastIntent.putExtra(RESULT_CODE, RESULT_OK); broadcastIntent.putExtra(ENDPOINT_URL, baseUri); broadcastIntent.putExtra(API_TYPE, entry.getKey().ordinal()); sendBroadcast(broadcastIntent); return; } } catch (IOException e) { // Network error. Notify the listeners and return. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NETWORK)); return; } } } // End of the loop was reached without finding an API endpoint. Send error code to the BroadcastReceiver. sendBroadcast(broadcastIntent.putExtra(RESULT_CODE, RESULT_FAIL_NO_API)); }
From source file:com.datastore_android_sdk.okhttp.OkHttpStack.java
License:Open Source License
@Override public URLHttpResponse performRequest(Request<?> request, ArrayList<HttpParamsEntry> additionalHeaders) throws IOException { 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()); for (final HttpParamsEntry entry : request.getHeaders()) { okHttpRequestBuilder.addHeader(entry.k, entry.v); }/*from ww w . jav a2s . c o m*/ for (final HttpParamsEntry entry : additionalHeaders) { okHttpRequestBuilder.addHeader(entry.k, entry.v); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); return responseFromConnection(okHttpResponse); }
From source file:com.dzhyun.sdk.DzhChannel.java
License:Open Source License
@ReactMethod public void connect(final String url, final int id) { OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(10, TimeUnit.SECONDS); client.setWriteTimeout(10, TimeUnit.SECONDS); // Disable timeouts for read client.setReadTimeout(0, TimeUnit.MINUTES); Request request = new Request.Builder().tag(id).url(url).build(); WebSocketCall.create(client, request).enqueue(new WebSocketListener() { @Override//from w w w . j av a 2s .c o m public void onOpen(WebSocket webSocket, Response response) { mWebSocketConnections.put(id, webSocket); WritableMap params = Arguments.createMap(); params.putInt("id", id); sendEvent("dzhChannelOpen", params); } @Override public void onClose(int code, String reason) { WritableMap params = Arguments.createMap(); params.putInt("id", id); params.putInt("code", code); params.putString("reason", reason); sendEvent("dzhChannelClosed", params); } @Override public void onFailure(IOException e, Response response) { notifyWebSocketFailed(id, e.getMessage()); } @Override public void onPong(Buffer buffer) { } @Override public void onMessage(BufferedSource bufferedSource, WebSocket.PayloadType payloadType) { String message; if (payloadType == WebSocket.PayloadType.BINARY) { try { message = Pb2Json.toJson(bufferedSource.readByteArray()); bufferedSource.close(); } catch (IOException e) { FLog.e(ReactConstants.TAG, "decode pb failed " + id, e); return; } } else { try { message = bufferedSource.readUtf8(); } catch (IOException e) { notifyWebSocketFailed(id, e.getMessage()); return; } try { bufferedSource.close(); } catch (IOException e) { FLog.e(ReactConstants.TAG, "Could not close BufferedSource for WebSocket id " + id, e); } } WritableMap params = Arguments.createMap(); params.putInt("id", id); params.putString("data", message); sendEvent("dzhChannelMessage", params); } }); // Trigger shutdown of the dispatcher's executor so this process can exit cleanly client.getDispatcher().getExecutorService().shutdown(); }
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 w w.j a v a2 s. com 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/*from w ww.j a 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;//from ww w .jav a2 s.com 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()); }