Example usage for com.squareup.okhttp OkHttpClient setWriteTimeout

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

Introduction

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

Prototype

public void setWriteTimeout(long timeout, TimeUnit unit) 

Source Link

Document

Sets the default write timeout for new connections.

Usage

From source file:com.mycelium.wapi.api.WapiClient.java

License:Apache License

/**
 * Attempt to connect and send to a URL in our list of URLS, if it fails try
 * the next until we have cycled through all URLs. timeout.
 *//*from  w w  w  .  ja va 2 s  .  c  o m*/
private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();
    while (true) {
        // currently active server-endpoint
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " ("
                    + _serverEndpoints.getCurrentEndpointIndex() + ")");

            // configure TimeOuts
            client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setReadTimeout(timeout, TimeUnit.MILLISECONDS);
            client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS);

            Stopwatch callDuration = Stopwatch.createStarted();
            // build request
            final String toSend = getPostBody(request);
            Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode)
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("Wapi %s finished (%dms)", function,
                    callDuration.elapsed(TimeUnit.MILLISECONDS)));

            // Check for status code 2XX
            if (response.isSuccessful()) {
                if (serverEndpoint instanceof FeedbackEndpoint) {
                    ((FeedbackEndpoint) serverEndpoint).onSuccess();
                }
                return response;
            } else {
                // If the status code is not 200 we cycle to the next server
                logError(String.format("Http call to %s failed with %d %s", function, response.code(),
                        response.message()));
                // throw...
            }
        } catch (IOException e) {
            logError("IOException when sending request " + function, e);
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }
        // Try the next server
        _serverEndpoints.switchToNextEndpoint();
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }

    }
}

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

License:Open Source License

@Provides
@Singleton//from   ww w.j a  va  2  s  .  c  o 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  av  a  2 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.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));
    }/*from  w  ww  .  j  av  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, 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);
    }//from  w  w  w  . j  a v  a  2s.  co  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 w w  . j ava2 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   w w w  .j a  v a2s . 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();
}

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 www .  j av a2 s.co 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  ava2  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;
}