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.facebook.buck.cli.BuckConfig.java

License:Apache License

private ArtifactCache createHttpArtifactCache() {
    URL url;/*from   w ww .  j  a va2  s.co m*/
    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());
}

From source file:com.facebook.buck.cli.BuildCommand.java

License:Apache License

private int executeDistributedBuild(CommandRunnerParams params) throws IOException {
    ProjectFilesystem filesystem = params.getCell().getFilesystem();

    if (distributedBuildStateFile != null) {
        Path stateDumpPath = Paths.get(distributedBuildStateFile);
        TTransport transport;//from w w w .  ja v a2s.  c o m
        boolean loading = Files.exists(stateDumpPath);
        if (loading) {
            transport = new TIOStreamTransport(filesystem.newFileInputStream(stateDumpPath));
        } else {
            transport = new TIOStreamTransport(filesystem.newFileOutputStream(stateDumpPath));
        }
        transport = new TZlibTransport(transport);
        TProtocol protocol = new TTupleProtocol(transport);

        try {
            if (loading) {
                DistributedBuildState state = DistributedBuildState.load(protocol);
                BuckConfig buckConfig = state.createBuckConfig(filesystem);
                params.getBuckEventBus()
                        .post(ConsoleEvent.info("Done loading state. Aliases: %s", buckConfig.getAliases()));
            } else {
                BuckConfig buckConfig = params.getBuckConfig();
                BuildJobState jobState = DistributedBuildState.dump(buckConfig);
                jobState.write(protocol);
                transport.flush();
            }
        } catch (TException e) {
            throw new RuntimeException(e);
        } finally {
            transport.close();
        }
    }

    DistBuildConfig config = new DistBuildConfig(params.getBuckConfig());
    ClientSideSlb slb = config.getFrontendConfig().createHttpClientSideSlb(params.getClock(),
            params.getBuckEventBus());
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setReadTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
    client.setWriteTimeout(config.getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS);

    try (HttpService httpService = new LoadBalancedService(slb, client, params.getBuckEventBus());
            ThriftService<FrontendRequest, FrontendResponse> service = new ThriftOverHttpService<>(
                    ThriftOverHttpServiceConfig.of(httpService))) {
        DistributedBuild build = new DistributedBuild(new DistBuildService(service, params.getBuckEventBus()));
        return build.executeAndPrintFailuresToEventBus();
    }
}

From source file:com.frostwire.http.HttpClient.java

License:Open Source License

private static OkHttpClient buildDefaultClient() {
    OkHttpClient c = new OkHttpClient();

    c.setFollowRedirects(true);//w  w w  . j  a v  a2s .  c om
    c.setFollowSslRedirects(true);
    c.setConnectTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setReadTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS);
    c.setHostnameVerifier(buildHostnameVerifier());
    c.setSslSocketFactory(buildSSLSocketFactory());
    c.interceptors().add(new GzipInterceptor());

    return c;
}

From source file:com.fullcontact.api.libs.fullcontact4j.http.FCUrlClient.java

License:Apache License

private static OkHttpClient generateDefaultOkHttp() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return client;
}

From source file:com.gezhii.fitgroup.network.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();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    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();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//from   w ww . j  a v  a2 s  .  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:com.github.leonardoxh.ywheaterdata.Utils.java

License:Apache License

static OkHttpClient defaultOkHttpClient() {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_UNIT);
    okHttpClient.setReadTimeout(DEFAULT_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_UNIT);
    okHttpClient.setWriteTimeout(DEFAULT_CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT_UNIT);
    return okHttpClient;
}

From source file:com.goforer.base.module.BaseGlideModule.java

License:Apache License

@Override
public void registerComponents(Context context, Glide glide) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    glide.register(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(client));
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.core.internal.BaseRequest.java

License:Apache License

/**
 * Sets the timeout for this resource request.
 *
 * @param timeout The timeout for this request procedure
 *///from   w w w  .  jav  a2 s. com
public void setTimeout(int timeout) {
    this.timeout = timeout;

    OkHttpClient client = getHttpClient();

    client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);
}

From source file:com.ibm.watson.developer_cloud.service.WatsonService.java

License:Open Source License

/**
 * Configures the HTTP client./*w w  w  . j a v a 2  s .c  o m*/
 * 
 * @return the HTTP client
 */
protected OkHttpClient configureHttpClient() {
    final OkHttpClient client = new OkHttpClient();
    final CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    client.setCookieHandler(cookieManager);

    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.setWriteTimeout(60, TimeUnit.SECONDS);
    client.setReadTimeout(90, TimeUnit.SECONDS);
    return client;
}

From source file:com.ichg.service.volley.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();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }/* w ww  .  j  a  v  a  2  s  .c om*/
    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;
}