Example usage for com.squareup.okhttp OkHttpClient setReadTimeout

List of usage examples for com.squareup.okhttp OkHttpClient setReadTimeout

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient setReadTimeout.

Prototype

public void setReadTimeout(long timeout, TimeUnit unit) 

Source Link

Document

Sets the default read timeout for new connections.

Usage

From source file:com.arnaudpiroelle.marvel.api.rest.client.RetrofitHttpClient.java

License:Apache License

private static OkUrlFactory generateDefaultOkUrlFactory() {
    OkHttpClient client = new com.squareup.okhttp.OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_SEC, TimeUnit.SECONDS);
    client.setReadTimeout(READ_TIMEOUT_SEC, TimeUnit.SECONDS);

    try {/*from ww w.  j  ava  2 s . c  o m*/
        File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
        Cache cache = new Cache(cacheDir, 1024);
        client.setCache(cache);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new OkUrlFactory(client);
}

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);
    }/*from   www  .  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 ww w  .ja  v  a  2 s  .c om
    } 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);
    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);//from  w w  w. j av a 2 s .  c  om

    return client;
}

From source file:com.camnter.easygank.gank.EasyGank.java

License:Open Source License

private EasyGank() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);

    /*/*from w w  w  .j  ava  2s  .  c  o  m*/
     * ??
     */
    if (EasyApplication.getInstance().log) {
        okHttpClient.interceptors().add(chain -> {
            Response response = chain.proceed(chain.request());
            com.orhanobut.logger.Logger.d(chain.request().urlString());
            return response;
        });
    }

    Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create(EasyApplication.getInstance().gson))
            .client(okHttpClient).build();
    this.gankService = retrofit.create(GankService.class);
}

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;/*from   ww  w .  ja v  a2 s . 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.  ja va  2s .  c om*/
    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   www .j  a v  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.ja v  a2s .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  ww. ja v a  2s  .  c  om
        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());
}