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.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   ww w  . j  a  v a  2s.  c  o 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();
}

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();//  w ww .j  a  va2 s  .  c  om
    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 .com
        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.HttpClient.java

License:Apache License

@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest,
        Optional<com.spotify.apollo.Request> apolloIncomingRequest) {

    final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
        final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse)
                .orElse(DEFAULT_CONTENT_TYPE);
        return RequestBody.create(contentType, payload);
    });//  ww w  .j  a  v  a  2s  .c o m

    Headers.Builder headersBuilder = new Headers.Builder();
    apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v));

    apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER))
            .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header));

    final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null))
            .url(apolloRequest.uri()).headers(headersBuilder.build()).build();

    final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();

    //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
    OkHttpClient finalClient = client;
    if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
        finalClient = client.clone();
        finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
    }

    finalClient.newCall(request).enqueue(TransformingCallback.create(result));

    return result;
}

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//w ww  .java2  s  .  com
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.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java

License:Open Source License

/**
 * Builds a RestAdapter.//from w  w w  .j  a  v  a2 s .  c o m
 */
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);
    client.setWriteTimeout(10, SECONDS);

    File cacheDir = new File(app.getCacheDir(), "http");
    Cache cache = new Cache(cacheDir, DISK_CACHE_SIZE);
    client.setCache(cache);//from   w w w .  j  a v  a 2  s  . c  o m

    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 w  w  w  . ja  v a 2 s.  c om
    // 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;
}