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.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);/*www.jav a 2s. c  o  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 o  m*/
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.lobobrowser.LoboBrowser.java

License:Open Source License

/**
 * Initializes the global URLStreamHandlerFactory.
 * <p>/*w w  w.  j  a  v a 2s  .c o m*/
 * This method is invoked by {@link #init(boolean, boolean)}.
 */
public static void initProtocols(final SSLSocketFactory sslSocketFactory) {
    // Configure URL protocol handlers
    final PlatformStreamHandlerFactory factory = PlatformStreamHandlerFactory.getInstance();
    URL.setURLStreamHandlerFactory(factory);
    final OkHttpClient okHttpClient = new OkHttpClient();

    final ArrayList<Protocol> protocolList = new ArrayList<>(2);
    protocolList.add(Protocol.HTTP_1_1);
    protocolList.add(Protocol.HTTP_2);
    okHttpClient.setProtocols(protocolList);

    okHttpClient.setConnectTimeout(100, TimeUnit.SECONDS);

    // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    okHttpClient.setSslSocketFactory(sslSocketFactory);
    okHttpClient.setFollowRedirects(false);
    okHttpClient.setFollowSslRedirects(false);
    factory.addFactory(new OkUrlFactory(okHttpClient));
    factory.addFactory(new LocalStreamHandlerFactory());
}

From source file:com.maxleapmobile.gitmaster.api.ApiManager.java

License:Open Source License

private ApiManager() {
    mContext = GithubApplication.getInstance();

    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
    okHttpClient.interceptors().add(new Interceptor() {
        @Override//from  w ww  . java2 s .  com
        public Response intercept(Chain chain) throws IOException {
            mAccessToken = PreferenceUtil.getString(mContext, Const.ACCESS_TOKEN_KEY, null);
            HttpUrl url;
            if (mAccessToken != null) {
                url = chain.request().httpUrl().newBuilder().addQueryParameter("access_token", mAccessToken)
                        .build();
            } else {
                url = chain.request().httpUrl();
            }

            Request request = chain.request();
            Request newRequest;
            newRequest = request.newBuilder().url(url).addHeader("User-Agent", USER_AGENT)
                    .addHeader("Accept", ACCEPT).build();
            return chain.proceed(newRequest);
        }
    });
    mRetrofit = new Retrofit.Builder().baseUrl(API_URL).client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

    mGithubApi = mRetrofit.create(GithubApi.class);
}

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));
    }//from www  . j a v  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.mtnfog.metatext.MetaTextStandardClient.java

License:Apache License

/**
 * Initialize a new client with your API key.
 * @param apiKey Your MetaText API key./* www  .  j a  v  a 2s  .  c o m*/
 */
public MetaTextStandardClient(String apiKey, String endpoint) {

    this.apiKey = apiKey;

    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(120, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(120, TimeUnit.SECONDS);

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(endpoint)
            .setConverter(new GsonConverter(new Gson())).setClient(new OkClient(okHttpClient)).build();

    service = restAdapter.create(MetaTextService.class);

}

From source file:com.mvcoding.financius.api.ApiModule.java

License:Open Source License

@Provides
@Singleton//from  w w w. j a va2  s  . c  o 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.  j av a  2 s.com
            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;
        }
    }
}

From source file:com.mycelium.wallet.external.cashila.api.CashilaService.java

License:Microsoft Reference Source License

public CashilaService(String baseUrl, String apiVersion, Bus eventBus) {
    this.baseUrl = baseUrl;
    this.eventBus = eventBus;

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(5000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(5000, TimeUnit.MILLISECONDS);
    client.networkInterceptors().add(hmacInterceptor);
    CertificatePinner certPinner = new CertificatePinner.Builder().add("cashila.com", CASHILA_CERT)
            .add("cashila-staging.com", CASHILA_CERT).build();
    client.setCertificatePinner(certPinner);

    // use jackson as json mapper, as we already use it in the rest of the project
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    objectMapper.registerModule(new WapiJsonModule());

    RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + apiVersion + "/")
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            //.setLogLevel(RestAdapter.LogLevel.FULL)
            .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client))
            .setRequestInterceptor(apiIdInterceptor).build();

    cashila = adapter.create(Cashila.class);

    // initialise nonce with current time and increase by one on each call
    lastNonce = System.currentTimeMillis();
}

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.j  a  va 2  s  .  c  om
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;
        }

    }
}