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: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);//from  ww w  . j  a v a  2s  . c  o  m
    client.setWriteTimeout(10, SECONDS);
    return client;
}

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  ww  w.  j  a  v  a  2s .  c  om*/
        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.amahi.anywhere.server.ApiConnectionDetector.java

License:Open Source License

private OkHttpClient buildHttpClient() {
    OkHttpClient httpClient = new OkHttpClient();

    httpClient.setConnectTimeout(Connection.TIMEOUT, TimeUnit.SECONDS);

    return httpClient;
}

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

License:Apache License

void refresh() throws IOException {
    try {/*from   ww  w  . j  a  v  a 2  s.co  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 {//w  ww. j  av  a  2 s . com
        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  .  j  ava  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   ww  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//www  . j  a v  a  2s  .  co  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.getlantern.firetweet.extension.streaming.util.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    if (ignoreSSLError) {
        client.setSslSocketFactory(SSLCertificateSocketFactory.getInsecure(0, null));
    } else {/*from   w w  w .j  a  va 2  s. c o  m*/
        client.setSslSocketFactory(SSLCertificateSocketFactory.getDefault(0, null));
    }
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier());
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.getlantern.firetweet.util.net.OkHttpClientImpl.java

License:Open Source License

private OkHttpClient createHttpClient(HttpClientConfiguration conf) {
    final OkHttpClient client = new OkHttpClient();
    final boolean ignoreSSLError = conf.isSSLErrorIgnored();
    final SSLCertificateSocketFactory sslSocketFactory;
    if (ignoreSSLError) {
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getInsecure(0, null);
    } else {//from   ww w.j a  v a 2  s. c  om
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new FiretweetTrustManager(context)});
    //        client.setHostnameVerifier(new HostResolvedHostnameVerifier(context, ignoreSSLError));
    client.setSslSocketFactory(sslSocketFactory);
    client.setSocketFactory(SocketFactory.getDefault());
    client.setConnectTimeout(conf.getHttpConnectionTimeout(), TimeUnit.MILLISECONDS);

    if (conf.isProxyConfigured()) {
        client.setProxy(new Proxy(Type.HTTP,
                InetSocketAddress.createUnresolved(conf.getHttpProxyHost(), conf.getHttpProxyPort())));
    }
    Internal.instance.setNetwork(client, new Network() {
        @Override
        public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException {
            try {
                return resolver.resolve(host);
            } catch (IOException e) {
                Crashlytics.logException(e);

                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}