Example usage for com.squareup.okhttp OkHttpClient setConnectTimeout

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

Introduction

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

Prototype

public void setConnectTimeout(long timeout, TimeUnit unit) 

Source Link

Document

Sets the default connect timeout for new connections.

Usage

From source file:com.nabilhachicha.kc.di.DataModule.java

License:Apache License

static OkHttpClient createOkHttpClient(Application app) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);
    client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.SECONDS);

    // Install an HTTP cache in the application cache directory.
    try {// w w w. j a v  a2s . co  m
        File cacheDir = new File(app.getCacheDir(), "http");
        Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
        client.setCache(cache);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return client;
}

From source file:com.netflix.spinnaker.fiat.shared.FiatAuthenticationConfig.java

License:Apache License

@Bean
@ConditionalOnMissingBean(FiatService.class) // Allows for override
public FiatService fiatService(FiatClientConfigurationProperties fiatConfigurationProperties,
        SpinnakerRequestInterceptor interceptor, OkHttpClientConfiguration okHttpClientConfiguration) {
    // New role providers break deserialization if this is not enabled.
    val objectMapper = new ObjectMapper();
    objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    OkHttpClient okHttpClient = okHttpClientConfiguration.create();

    if (fiatConfigurationProperties.getConnectTimeoutMs() != null) {
        okHttpClient.setConnectTimeout(fiatConfigurationProperties.getConnectTimeoutMs(),
                TimeUnit.MILLISECONDS);
    }/*w w  w. j  a  v a2  s. co m*/

    if (fiatConfigurationProperties.getReadTimeoutMs() != null) {
        okHttpClient.setConnectTimeout(fiatConfigurationProperties.getReadTimeoutMs(), TimeUnit.MILLISECONDS);
    }

    return new RestAdapter.Builder()
            .setEndpoint(Endpoints.newFixedEndpoint(fiatConfigurationProperties.getBaseUrl()))
            .setRequestInterceptor(interceptor).setClient(new OkClient(okHttpClient))
            .setConverter(new JacksonConverter(objectMapper)).setLogLevel(retrofitLogLevel)
            .setLog(new Slf4jRetrofitLogger(FiatService.class)).build().create(FiatService.class);
}

From source file:com.netflix.spinnaker.igor.concourse.client.OkHttpClientBuilder.java

License:Apache License

public static OkHttpClient retryingClient(Supplier<Token> refreshToken) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.interceptors().add(chain -> OkHttpClientBuilder.createRetryInterceptor(chain, refreshToken));
    okHttpClient.setHostnameVerifier((s, sslSession) -> true);
    okHttpClient.setSslSocketFactory(getSslContext().getSocketFactory());
    okHttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(15, TimeUnit.SECONDS);
    return okHttpClient;
}

From source file:com.pacoworks.dereference.dependencies.modules.NetworkModule.java

License:Open Source License

@Provides
@Singleton/*  w w w  .  j  ava2  s.co m*/
OkHttpClient provideOkHttp(final Cache cache, LoggerInterceptor loggerInterceptor,
        StethoInterceptor stethoInterceptor) {
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(cache);
    okHttpClient.networkInterceptors().add(loggerInterceptor);
    okHttpClient.networkInterceptors().add(stethoInterceptor);
    okHttpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    okHttpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return okHttpClient;
}

From source file:com.peach.masktime.module.net.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();
    LogUtils.i(TAG, "timeoutMs = " + timeoutMs);
    client.setProxy(Proxy.NO_PROXY);
    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  w w.j a v  a2  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.phattn.vnexpressnews.io.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  w 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, length = responseHeaders.size(); i < length; i++) {
        final String name = responseHeaders.name(i);
        final String value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}

From source file:com.raskasa.dropwizard.okhttp.OkHttpClientBuilder.java

License:Apache License

/** Builds the {@link OkHttpClient}. */
public OkHttpClient build() {
    final OkHttpClient rawClient = new OkHttpClient();
    if (configuration.getConnectTimeout() > 0L) {
        rawClient.setConnectTimeout(configuration.getConnectTimeout(), TimeUnit.MILLISECONDS);
    }/*www  .j av a2  s. c  o  m*/
    if (configuration.getReadTimeout() > 0L) {
        rawClient.setReadTimeout(configuration.getReadTimeout(), TimeUnit.MILLISECONDS);
    }
    if (configuration.getWriteTimeout() > 0L) {
        rawClient.setWriteTimeout(configuration.getWriteTimeout(), TimeUnit.MILLISECONDS);
    }
    if (configuration.getCacheDir() != null && configuration.getCacheSize() > 0L) {
        rawClient.setCache(new Cache(configuration.getCacheDir(), configuration.getCacheSize()));
    }
    final OkHttpClient client = InstrumentedOkHttpClients.create(registry, rawClient, name);

    // If the environment is present, we tie the client with the server lifecycle
    if (environment != null) {
        environment.lifecycle().manage(new Managed() {
            @Override
            public void start() throws Exception {
            }

            @Override
            public void stop() throws Exception {
                client.getConnectionPool().evictAll();
            }
        });
    }
    return client;
}

From source file:com.raskasa.oksolr.SolrClient.java

License:Apache License

private OkHttpClient createOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);/*from w  ww. ja  va  2 s  . co  m*/
    client.setWriteTimeout(10, SECONDS);
    return client;
}

From source file:com.raskasa.oksolr.SolrClientTest.java

License:Apache License

@Test
public void testCustomTimeout() throws Exception {
    OkHttpClient okClient = new OkHttpClient();
    okClient.setConnectTimeout(20, SECONDS);
    okClient.setReadTimeout(20, SECONDS);
    okClient.setWriteTimeout(20, SECONDS);
    SolrClient solrClient = new SolrClient(okClient);

    assertThat(solrClient.getConnectTimeout()).isEqualTo(20000); // 20 secs
    assertThat(solrClient.getReadTimeout()).isEqualTo(20000); // 20 secs
    assertThat(solrClient.getWriteTimeout()).isEqualTo(20000); // 20 secs
}

From source file:com.raskasa.solrfit.SolrResponseTest.java

License:Apache License

@Test
public void testSimpleResponse() throws Exception {
    // Create a MockWebServer. These are lean enough that you can create a new
    // instance for every unit test.
    MockWebServer server = new MockWebServer();

    // Schedule some responses.
    server.enqueue(new MockResponse().setBody(loadJsonFile("simple.json")));

    // Start the server.
    server.start();//from  www  .  ja va2s .co m

    // Ask the server for its URL. You'll need this to make HTTP requests.
    URL baseUrl = server.getUrl("/");

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);
    client.setWriteTimeout(10, SECONDS);

    RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(client))
            .setEndpoint(baseUrl.toString()).build();

    SimpleApi api = restAdapter.create(SimpleApi.class);
    User user = api.getUser();

    assertThat(user.firstName).isEqualTo("Ras Kasa");
    assertThat(user.lastName).isEqualTo("Williams");

    // Shut down the server. Instances cannot be reused.
    server.shutdown();
}