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:net.callmeike.android.simplesync.net.NetModule.java

License:Apache License

static OkHttpClient createOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, SECONDS);
    client.setReadTimeout(10, SECONDS);
    client.setWriteTimeout(10, SECONDS);
    return client;
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

protected void executeUploadAsync(HttpCallback callback, String url, Object tag, StrParam[] strParams,
        IOParam... IOParams) {/*from  www . j  a v a 2  s . c om*/
    Request.Builder builder = mBuilder.builderPost(url, strParams, IOParams);
    if (null != IOParams && IOParams.length > 1) {//????60
        OkHttpClient client = mOkHttpClient.clone();
        long time = 60 * 1000 * IOParams.length;
        client.setReadTimeout(time, TimeUnit.MILLISECONDS);
        uploadAsync(client, builder, tag, callback);
    } else {
        uploadAsync(builder, tag, callback);
    }
}

From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java

License:Open Source License

public <S> S request(Class<S> service, String username, String password) {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(60, TimeUnit.SECONDS);
    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.interceptors().add(new AuthenticationInterceptor(username, password));
    client.interceptors().add(new Interceptor() {
        @Override/*from   w w w  .jav  a 2 s. co  m*/
        public Response intercept(Chain chain) throws IOException {
            com.squareup.okhttp.Request request = chain.request();
            Response response = chain.proceed(request);

            int retryCount = 0;
            while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) {
                Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS);
                response = chain.proceed(request);
                retryCount++;
            }
            if (!response.isSuccessful())
                log.error(request.urlString() + " request failed.");

            return response;
        }
    });

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new TaskboardJacksonModule());
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl())
            .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build();

    return retrofit.create(service);
}

From source file:org.apache.hadoop.hdfs.web.oauth2.ConfRefreshTokenBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {//  w  w  w. jav a2 s.  c o  m
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(GRANT_TYPE, REFRESH_TOKEN, REFRESH_TOKEN, refreshToken, CLIENT_ID,
                clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        accessTokenTimer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();
    } catch (Exception e) {
        throw new IOException("Exception while refreshing access token", e);
    }
}

From source file:org.apache.hadoop.hdfs.web.oauth2.CredentialBasedAccessTokenProvider.java

License:Apache License

void refresh() throws IOException {
    try {/* ww w .  j av  a  2  s .  c  o m*/
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
        client.setReadTimeout(URLConnectionFactory.DEFAULT_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);

        String bodyString = Utils.postBody(CLIENT_SECRET, getCredential(), GRANT_TYPE, CLIENT_CREDENTIALS,
                CLIENT_ID, clientId);

        RequestBody body = RequestBody.create(URLENCODED, bodyString);

        Request request = new Request.Builder().url(refreshURL).post(body).build();
        Response responseBody = client.newCall(request).execute();

        if (responseBody.code() != HttpStatus.SC_OK) {
            throw new IllegalArgumentException("Received invalid http response: " + responseBody.code()
                    + ", text = " + responseBody.toString());
        }

        Map<?, ?> response = READER.readValue(responseBody.body().string());

        String newExpiresIn = response.get(EXPIRES_IN).toString();
        timer.setExpiresIn(newExpiresIn);

        accessToken = response.get(ACCESS_TOKEN).toString();

    } catch (Exception e) {
        throw new IOException("Unable to obtain access token from credential", e);
    }
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@OnScheduled
public void setUpClient(final ProcessContext context) throws IOException {
    okHttpClientAtomicReference.set(null);

    OkHttpClient okHttpClient = new OkHttpClient();

    // Add a proxy if set
    final String proxyHost = context.getProperty(PROP_PROXY_HOST).getValue();
    final Integer proxyPort = context.getProperty(PROP_PROXY_PORT).asInteger();
    if (proxyHost != null && proxyPort != null) {
        final Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        okHttpClient.setProxy(proxy);/*from  w w w  .  jav a  2 s.co  m*/
    }

    // Set timeouts
    okHttpClient.setConnectTimeout(
            (context.getProperty(PROP_CONNECT_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue()),
            TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(
            context.getProperty(PROP_READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue(),
            TimeUnit.MILLISECONDS);

    // Set whether to follow redirects
    okHttpClient.setFollowRedirects(context.getProperty(PROP_FOLLOW_REDIRECTS).asBoolean());

    final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(ClientAuth.NONE);

    // check if the ssl context is set and add the factory if so
    if (sslContext != null) {
        okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
    }

    // check the trusted hostname property and override the HostnameVerifier
    String trustedHostname = trimToEmpty(context.getProperty(PROP_TRUSTED_HOSTNAME).getValue());
    if (!trustedHostname.isEmpty()) {
        okHttpClient.setHostnameVerifier(
                new OverrideHostnameVerifier(trustedHostname, okHttpClient.getHostnameVerifier()));
    }

    setAuthenticator(okHttpClient, context);

    useChunked = context.getProperty(PROP_USE_CHUNKED_ENCODING).asBoolean();

    okHttpClientAtomicReference.set(okHttpClient);
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Pushes data to DHIS Server//from w  w w  . j a  v a  2 s .  com
 * @param data
 */
public JSONObject pushData(JSONObject data) throws Exception {
    Response response = null;

    final String DHIS_URL = getDhisURL() + DHIS_PUSH_API;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout
    client.setRetryOnConnectionFailure(false); // Cancel retry on failure
    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Log.d(TAG, "Url" + DHIS_URL + "");
    RequestBody body = RequestBody.create(JSON, data.toString());
    Request request = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL)
            .post(body).build();

    response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        Log.e(TAG, "pushData (" + response.code() + "): " + response.body().string());
        throw new IOException(response.message());
    }
    return parseResponse(response.body().string());
}

From source file:org.eyeseetea.malariacare.network.NetworkUtils.java

License:Open Source License

/**
 * Call to DHIS Server/*from  w  w w  .  j  a  v a 2s.c  o m*/
 * @param data
 * @param url
 */
public Response executeCall(JSONObject data, String url, String method) throws IOException {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
    final String DHIS_URL = sharedPreferences.getString(applicationContext.getString(R.string.dhis_url),
            applicationContext.getString(R.string.login_info_dhis_default_server_url)) + url;

    OkHttpClient client = UnsafeOkHttpsClientFactory.getUnsafeOkHttpClient();

    client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(30, TimeUnit.SECONDS); // socket timeout
    client.setWriteTimeout(30, TimeUnit.SECONDS); // write timeout
    client.setRetryOnConnectionFailure(false); // Cancel retry on failure

    BasicAuthenticator basicAuthenticator = new BasicAuthenticator();
    client.setAuthenticator(basicAuthenticator);

    Request.Builder builder = new Request.Builder()
            .header(basicAuthenticator.AUTHORIZATION_HEADER, basicAuthenticator.getCredentials()).url(DHIS_URL);

    switch (method) {
    case "POST":
        RequestBody postBody = RequestBody.create(JSON, data.toString());
        builder.post(postBody);
        break;
    case "PUT":
        RequestBody putBody = RequestBody.create(JSON, data.toString());
        builder.put(putBody);
        break;
    case "PATCH":
        RequestBody patchBody = RequestBody.create(JSON, data.toString());
        builder.patch(patchBody);
        break;
    case "GET":
        builder.get();
        break;
    }

    Request request = builder.build();
    return client.newCall(request).execute();
}

From source file:org.graylog2.shared.bindings.providers.OkHttpClientProvider.java

License:Open Source License

@Override
public OkHttpClient get() {
    final OkHttpClient client = new OkHttpClient();
    client.setRetryOnConnectionFailure(true);
    client.setConnectTimeout(connectTimeout.getQuantity(), connectTimeout.getUnit());
    client.setWriteTimeout(writeTimeout.getQuantity(), writeTimeout.getUnit());
    client.setReadTimeout(readTimeout.getQuantity(), readTimeout.getUnit());

    if (httpProxyUri != null) {
        final Proxy proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(httpProxyUri.getHost(), httpProxyUri.getPort()));
        client.setProxy(proxy);// w ww.  j  ava 2  s .c om
    }

    return client;
}

From source file:org.hawkular.agent.commandcli.CommandCli.java

License:Apache License

private static CliWebSocketListener sendCommand(Config config) throws Exception {

    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.MINUTES);

    Request request = new Request.Builder().url(config.serverUrl)
            .addHeader("Authorization", Credentials.basic(config.username, config.password))
            .addHeader("Accept", "application/json").build();

    WebSocketCall wsc = WebSocketCall.create(httpClient, request);
    CliWebSocketListener listener = new CliWebSocketListener(httpClient, wsc, config);
    return listener;
}