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.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.hkm.root.Tasks.upload_data.java

License:Open Source License

public void execute_upload(Request requestBuild) throws IOException, Exception {
    // executes generic request
    OkHttpClient use_client = client.clone();
    use_client.setWriteTimeout(10, TimeUnit.SECONDS);
    Response response = use_client.newCall(requestBuild).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    } else {/*from  ww  w  .  j a v a  2 s .co  m*/
        if (!response.body().string().isEmpty()) {
            success_events_achieved++;
            // sb.append(response.body().string());
            System.out.println(response.body().string());
            // StandJsonResponse sp = new StandJsonResponse();
            // sp.fromString(response.body().string()).setSingleSuccessAction(success_pass_event).run();
        } else {
            throw new Exception("response body is empty");
        }
    }
}

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   www  .  ja v a 2 s. co m*/
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  va  2s .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));
    }//from w  w w  .j a  va  2s . 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;
}

From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java

License:Open Source License

protected OkHttpClient getClient(int connectionTimeout) {
    OkHttpClient clone = client.clone();

    clone.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
    clone.setReadTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
    clone.setWriteTimeout(connectionTimeout, TimeUnit.MILLISECONDS);

    clone.setFollowRedirects(false);/*from w ww .j  av a  2s  . co  m*/

    return clone;
}

From source file:com.linroid.pushapp.module.DataModule.java

License:Apache License

@Provides
@Singleton// w  w w .  ja  v a  2 s  . c om
OkHttpClient provideOkHttp(Cache cache) {
    OkHttpClient okHttp = new OkHttpClient();
    okHttp.setCache(cache);
    okHttp.setConnectTimeout(30, TimeUnit.SECONDS);
    okHttp.setReadTimeout(30, TimeUnit.SECONDS);
    okHttp.setWriteTimeout(30, TimeUnit.SECONDS);
    okHttp.networkInterceptors().add(new StethoInterceptor());
    return okHttp;
}

From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.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);
    client.networkInterceptors().add(new MoesifOkHttp2Interceptor());

    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.ja  va2 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.mvcoding.financius.api.ApiModule.java

License:Open Source License

@Provides
@Singleton//from  w w w  . j  av a2  s .  co  m
public RestAdapter provideRestAdapter(EndpointAuthenticator endpointAuthenticator,
        EndpointInterceptor endpointInterceptor) {
    final OkHttpClient httpClient = new OkHttpClient();
    httpClient.setAuthenticator(endpointAuthenticator);
    httpClient.setConnectTimeout(20, TimeUnit.SECONDS);
    httpClient.setReadTimeout(20, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(20, TimeUnit.SECONDS);

    return new RestAdapter.Builder().setClient(new OkClient(httpClient)).setEndpoint(ENDPOINT)
            .setRequestInterceptor(endpointInterceptor).setLogLevel(RestAdapter.LogLevel.FULL).build();
}

From source file:com.mycelium.lt.api.LtApiClient.java

License:Apache License

private Response getConnectionAndSendRequest(LtRequest request, int timeout) {
    int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex();

    // Figure what our current endpoint is. On errors we fail over until we
    // are back at the initial endpoint
    HttpEndpoint initialEndpoint = getEndpoint();
    while (true) {
        HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint();
        try {/*from  w  ww  .  ja  v  a2 s .co  m*/
            OkHttpClient client = serverEndpoint.getClient();
            _logger.logInfo("LT 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()
                    .post(RequestBody.create(MediaType.parse("application/json"), toSend))
                    .url(serverEndpoint.getUri(request.toString()).toString()).build();

            // execute request
            Response response = client.newCall(rq).execute();
            callDuration.stop();
            _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(),
                    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("Local Trader server request for class %s returned HTTP status code %d",
                        request.getClass().toString(), response.code()));
            }

        } catch (IOException e) {
            logError("getConnectionAndSendRequest failed IO exception.");
            if (serverEndpoint instanceof FeedbackEndpoint) {
                _logger.logInfo("Resetting tor");
                ((FeedbackEndpoint) serverEndpoint).onError();
            }
        }

        // We had an IO exception or a bad status, fail over and try again
        _serverEndpoints.switchToNextEndpoint();
        // Check if we are back at the initial endpoint, in which case we have
        // to give up
        if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) {
            // We have tried all URLs
            return null;
        }
    }
}