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.raskasa.solrfit.SolrResponseTest.java

License:Apache License

@Test
public void testSolrResponse() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setBody(loadJsonFile("solr.json")));
    server.start();//from w  ww  .java2s  .c o  m
    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();

    ExampleSolrApi solr = restAdapter.create(ExampleSolrApi.class);
    SolrQuery query = new SolrQuery.Builder().basic("", "").build();
    SolrResponse<State> response = solr.states(query);
    assertThat(response.internal.results.get(0).name).isEqualTo("New York");
    assertThat(response.internal.results.get(0).code).isEqualTo("NY");
    assertThat(response.internal.results.get(0).country).isEqualTo("United States");
    assertThat(response.internal.results.get(0).countryCode).isEqualTo("US");
    assertThat(response.internal.results.get(1).name).isEqualTo("California");
    assertThat(response.internal.results.get(1).code).isEqualTo("CA");
    assertThat(response.internal.results.get(1).country).isEqualTo("United States");
    assertThat(response.internal.results.get(1).countryCode).isEqualTo("US");
}

From source file:com.seu.mycircle.model.repository.toolbox.HttpManager.java

License:Apache License

public static Retrofit.Builder getBuilder(OkHttpClient client) {
    if (builder == null) {
        client.setReadTimeout(10, TimeUnit.MINUTES);
        client.setConnectTimeout(10, TimeUnit.MINUTES);
        client.setWriteTimeout(10, TimeUnit.MINUTES);

        //print/*from  w  w w  .  j  av  a  2  s .  c  o  m*/
        client.interceptors().add(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                if (message.startsWith("{")) {
                    Logger.json(message);
                } else {
                    Logger.i("ApiManger", message);
                }
            }
        }));

        //add custom headers
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("platform", "android")
                        .addHeader("appVersion", BuildConfig.VERSION_NAME).build();
                return chain.proceed(request);
            }
        });

        builder = new Retrofit.Builder().client(client).addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
    }
    return builder;
}

From source file:com.spotify.apollo.http.client.OkHttpClientProvider.java

License:Apache License

@Override
public OkHttpClient get() {
    final OkHttpClient client = new OkHttpClient();

    //timeouts settings
    config.connectTimeoutMillis().ifPresent(millis -> client.setConnectTimeout(millis, TimeUnit.MILLISECONDS));

    config.readTimeoutMillis().ifPresent(millis -> client.setReadTimeout(millis, TimeUnit.MILLISECONDS));

    config.writeTimeoutMillis().ifPresent(millis -> client.setWriteTimeout(millis, TimeUnit.MILLISECONDS));

    // connection pool settings
    client.setConnectionPool(new ConnectionPool(
            // defaults that come from com.squareup.okhttp.ConnectionPool
            config.maxIdleConnections().orElse(5),
            config.connectionKeepAliveDurationMillis().orElse(5 * 60 * 1000)));

    // async dispatcher settings
    config.maxAsyncRequests().ifPresent(max -> client.getDispatcher().setMaxRequests(max));

    config.maxAsyncRequestsPerHost().ifPresent(max -> client.getDispatcher().setMaxRequestsPerHost(max));

    closer.register(ExecutorServiceCloser.of(client.getDispatcher().getExecutorService()));

    return client;
}

From source file:com.squareup.picasso.OkHttpDownloader.java

License:Apache License

private static OkHttpClient defaultOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(Utils.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setReadTimeout(Utils.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(Utils.DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return client;
}

From source file:com.thanksmister.btcblue.data.api.ApiModule.java

License:Apache License

@Provides
@Singleton//from   w  ww.  ja v  a 2s.co m
Client provideClient(OkHttpClient client) {
    client = new OkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setConnectionPool(new ConnectionPool(0, 5 * 60 * 1000));
    return new OkClient(client);
}

From source file:com.twolinessoftware.network.BaseRetrofitHelper.java

License:Apache License

public BaseApiService newBaseApiService(String endpoint) {

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(endpoint)
            .setClient(new OkClient(okHttpClient)).setRequestInterceptor(apiRequestInterceptor)
            .setLogLevel(Config.RETROFIT_LOGLEVEL).setErrorHandler(apiErrorConverter)
            .setConverter(new GsonConverter(GsonUtil.buildGsonAdapter())).build();
    return restAdapter.create(BaseApiService.class);
}

From source file:com.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java

License:Open Source License

/**
 * Builds a RestAdapter./*  w  w w. java2  s  .c  om*/
 */
private static RestAdapter buildRestAdapter(final Session session, String endpointHost,
        final OAuth2Helper oAuth2Helper, RestAdapter.LogLevel logLevel, OkHttpClient httpClient)
        throws IOException {

    RequestInterceptor requestInterceptor = new RequestInterceptor() {

        @Override
        public void intercept(RequestFacade requestFacade) {
            Credential credential = session.getCredential();
            if (credential != null) {
                oAuth2Helper.refreshCredentialIfNeeded(credential);
                requestFacade.addHeader("Authorization", "Bearer " + credential.getAccessToken());
            } else {
                requestFacade.addHeader("Authorization", "Token " + session.getServerToken());
            }

            if (session.getLocale() != null) {
                requestFacade.addHeader("Accept-Language", session.getLocale().getLanguage());
            }

            requestFacade.addHeader("X-Uber-User-Agent", "Java Rides SDK v" + LIB_VERSION);
        }
    };

    if (httpClient == null) {
        httpClient = new OkHttpClient();
        httpClient.setConnectTimeout(1, TimeUnit.MINUTES);
        httpClient.setReadTimeout(1, TimeUnit.MINUTES);
        httpClient.setFollowRedirects(false);
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request oldRequest = chain.request();
                Response response = chain.proceed(oldRequest);
                if (response.isRedirect()) {
                    String redirectUrl = response.header(HttpHeaders.LOCATION);
                    Request newRequest = oldRequest.newBuilder().url(redirectUrl).build();
                    return chain.proceed(newRequest);
                }
                return response;
            }
        });
    }

    return new RestAdapter.Builder().setEndpoint(endpointHost)
            .setConverter(new GsonConverter(new GsonBuilder().create()))
            .setRequestInterceptor(requestInterceptor).setClient(new OkClient(httpClient)).setLogLevel(logLevel)
            .build();
}

From source file:com.uditgupta.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);//www.  j a  v  a  2 s  .co  m
    client.setWriteTimeout(10, SECONDS);

    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);

    return client;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

License:Apache License

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);/*from   ww  w.j  a va2  s.  c o  m*/
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:com.ushahidi.android.presentation.di.modules.AppModule.java

License:Open Source License

/**
 * Provides {@link HttpClientWrap} object
 *
 * @param context The calling context/*ww w  .j a  v  a 2 s  .  c  om*/
 * @return The http client wrap object
 */
@Provides
@Singleton
HttpClientWrap provideOkHttpClient(Context context) {
    final OkHttpClient okHttpClient = createOkHttpClient(context.getApplicationContext());
    okHttpClient.setCookieHandler(CookieHandler.getDefault());
    okHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
    okHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
    return new HttpClientWrap(context, new OkClient(okHttpClient));
}