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: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);//from   ww w. j  ava 2  s  . c o  m
    }

    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;
}

From source file:org.hawkular.agent.monitor.util.BaseHttpClientGenerator.java

License:Apache License

public BaseHttpClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    /* set the timeouts explicitly only if they were set through the config */
    configuration.getConnectTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setConnectTimeout(timeout.intValue(), TimeUnit.SECONDS));
    configuration.getReadTimeoutSeconds()
            .ifPresent(timeout -> httpClient.setReadTimeout(timeout.intValue(), TimeUnit.SECONDS));

    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }/*from  ww  w .j av  a2s. c om*/
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.hawkular.client.android.util.WebSocketClientGenerator.java

License:Apache License

public WebSocketClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    if (configuration.getConnectTimeoutSeconds() != -1) {
        httpClient.setConnectTimeout(configuration.getConnectTimeoutSeconds(), TimeUnit.SECONDS);
    }// ww w  . j  av  a 2s .c  o m

    if (configuration.getReadTimeoutSeconds() != -1) {
        httpClient.setReadTimeout(configuration.getReadTimeoutSeconds(), TimeUnit.SECONDS);
    }
    if (this.configuration.isUseSSL()) {
        SSLContext theSslContextToUse;

        if (this.configuration.getSslContext() == null) {
            if (this.configuration.getKeystorePath() != null) {
                theSslContextToUse = buildSSLContext(this.configuration.getKeystorePath(),
                        this.configuration.getKeystorePassword());
            } else {
                theSslContextToUse = null; // rely on the JVM default
            }
        } else {
            theSslContextToUse = this.configuration.getSslContext();
        }

        if (theSslContextToUse != null) {
            httpClient.setSslSocketFactory(theSslContextToUse.getSocketFactory());
        }

        // does not perform any hostname verification when looking at the remote end's cert
        /*
        httpClient.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            log.debugf("HTTP client is blindly approving cert for [%s]", hostname);
            return true;
        }
        });
        */
    }

    this.httpClient = httpClient;
}

From source file:org.hawkular.cmdgw.ws.test.TestWebSocketClient.java

License:Apache License

private TestWebSocketClient(Request request, TestListener testListener, int connectTimeoutSeconds,
        int readTimeoutSeconds) {
    super();//from  w  ww  .ja  va  2 s . co  m
    if (request == null) {
        throw new IllegalStateException(
                "Cannot build a [" + TestWebSocketClient.class.getName() + "] with a null request");
    }
    this.listener = testListener;
    OkHttpClient c = new OkHttpClient();
    c.setConnectTimeout(connectTimeoutSeconds, TimeUnit.SECONDS);
    c.setReadTimeout(readTimeoutSeconds, TimeUnit.SECONDS);
    this.client = c;

    WebSocketCall.create(client, request).enqueue(testListener);
}

From source file:org.mariotaku.twidere.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 {//w  w  w .  j ava 2  s.  co m
        sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0, null);
    }
    //        sslSocketFactory.setTrustManagers(new TrustManager[]{new TwidereTrustManager(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) {
                if (e instanceof UnknownHostException)
                    throw (UnknownHostException) e;
                throw new UnknownHostException("Unable to resolve address " + e.getMessage());
            }
        }
    });
    return client;
}

From source file:org.matrix.androidsdk.RestClient.java

License:Apache License

/**
 * Public constructor./*from   ww  w. ja  v a  2 s. com*/
 * @param hsUri The http[s] URI to the home server.
 */
public RestClient(Uri hsUri, Class<T> type) {
    // sanity check
    if (hsUri == null || (!"http".equals(hsUri.getScheme()) && !"https".equals(hsUri.getScheme()))) {
        throw new RuntimeException("Invalid home server URI: " + hsUri);
    }

    // The JSON -> object mapper
    gson = JsonUtils.getGson();

    // HTTP client
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    okHttpClient.setReadTimeout(READ_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    // Rest adapter for turning API interfaces into actual REST-calling objects
    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(hsUri.toString() + URI_PREFIX)
            .setConverter(new GsonConverter(gson)).setClient(new OkClient(okHttpClient))
            .setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestInterceptor.RequestFacade request) {
                    // Add the access token to all requests if it is set
                    if ((mCredentials != null) && (mCredentials.accessToken != null)) {
                        request.addEncodedQueryParam(PARAM_ACCESS_TOKEN, mCredentials.accessToken);
                    }
                }
            }).build();

    restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);

    mApi = restAdapter.create(type);
}

From source file:org.mythtv.services.api.ServerVersionQuery.java

License:Apache License

/**
 * Gets the api version of the given backend
 *
 * @param baseUri the backend services api url
 * @param connectTimeout connection timeout
 * @param timeUnit connection timeout unit
 * @return the Api version// w w  w.j  av a 2 s  .  co m
 * @throws IOException if an error occurs
 */
public static ApiVersion getMythVersion(String baseUri, long connectTimeout, TimeUnit timeUnit)
        throws IOException {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(connectTimeout, timeUnit);
    return getMythVersion(baseUri, client);
}

From source file:org.mythtv.services.api.ServerVersionQuery.java

License:Apache License

/**
 * Check if the server is reachable//from w w w .  j  a v a 2 s .c o  m
 *
 * @param baseUrl The url of the server to test
 * @param connectTimeout connection timeout
 * @param timeUnit connection timeout unit
 * @return true if reachable otherwise false.
 * @throws IOException if an error occurs
 */
public static boolean isServerReachable(String baseUrl, long connectTimeout, TimeUnit timeUnit)
        throws IOException {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(connectTimeout, timeUnit);
    return isServerReachable(baseUrl, client);
}

From source file:org.openlmis.core.network.LMISRestManager.java

License:Open Source License

protected Client getSSLClient() {
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.setReadTimeout(1, TimeUnit.MINUTES);
    httpClient.setConnectTimeout(15, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(30, TimeUnit.SECONDS);

    return new OkClient(httpClient);
}