Java Code Examples for com.squareup.okhttp.OkHttpClient#setConnectTimeout()

The following examples show how to use com.squareup.okhttp.OkHttpClient#setConnectTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HawkularMetricsClient.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param metricsServer
 */
public HawkularMetricsClient(URL metricsServer) {
    this.serverUrl = metricsServer;
    httpClient = new OkHttpClient();
    httpClient.setReadTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setFollowRedirects(true);
    httpClient.setFollowSslRedirects(true);
    httpClient.setProxySelector(ProxySelector.getDefault());
    httpClient.setCookieHandler(CookieHandler.getDefault());
    httpClient.setCertificatePinner(CertificatePinner.DEFAULT);
    httpClient.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    httpClient.setConnectionPool(ConnectionPool.getDefault());
    httpClient.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    httpClient.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    httpClient.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(httpClient, Network.DEFAULT);
}
 
Example 2
Source File: RestVolley.java    From RestVolley with Apache License 2.0 6 votes vote down vote up
/**
 * create a new http engine with tag that contains OkHttpClient and RequestQueue.
 * <br>
 * <br>
 * if the http engine with the special tag exists, return the existing http engine, otherwise create a new http engine and return.
 * @param context Context.
 * @param engineTag http engine Tag related to the http engine.
 * @return HttpEngine.
 */
public static RequestEngine newRequestEngine(Context context, String engineTag, boolean isStreamBased) {
    RequestEngine requestEngine = sRequestEngineMap.get(engineTag);
    if (requestEngine == null) {
        OkHttpClient okHttpClient = new OkHttpClient();

        okHttpClient.setConnectTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setWriteTimeout(DEFAULT_HTTP_TIMEOUT, TimeUnit.MILLISECONDS);
        okHttpClient.setSslSocketFactory(CertificateUtils.getDefaultSSLSocketFactory());
        okHttpClient.setHostnameVerifier(CertificateUtils.ALLOW_ALL_HOSTNAME_VERIFIER);

        RequestQueue requestQueue = newRequestQueue(context.getApplicationContext(), new OkHttpStack(okHttpClient), DEF_THREAD_POOL_SIZE, isStreamBased);
        requestQueue.start();

        requestEngine = new RequestEngine(requestQueue, okHttpClient);

        sRequestEngineMap.put(engineTag, requestEngine);
    }

    return requestEngine;
}
 
Example 3
Source File: HttpUtil.java    From AutoEx with Apache License 2.0 6 votes vote down vote up
public static void dogetHttp3(final String urls, final HResponse mHResponse) {
    try {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        Request build1 = new Request.Builder().url(urls).get().build();

        Response execute = client.newCall(build1).execute();
        if (execute == null || execute.body() == null) {
            mHResponse.onError("没有找到任何可参考的,真可惜。");
            return;
        }
        String string = execute.body().string();
        mHResponse.onFinish(string);
    } catch (IOException e) {
        e.printStackTrace();
        mHResponse.onError(e.getMessage());
    }
}
 
Example 4
Source File: HttpConnectorFactory.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * @return a new http client
 */
private OkHttpClient createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(connectorOptions.getReadTimeout(), TimeUnit.SECONDS);
    client.setWriteTimeout(connectorOptions.getWriteTimeout(), TimeUnit.SECONDS);
    client.setConnectTimeout(connectorOptions.getConnectTimeout(), TimeUnit.SECONDS);
    client.setFollowRedirects(connectorOptions.isFollowRedirects());
    client.setFollowSslRedirects(connectorOptions.isFollowRedirects());
    client.setProxySelector(ProxySelector.getDefault());
    client.setCookieHandler(CookieHandler.getDefault());
    client.setCertificatePinner(CertificatePinner.DEFAULT);
    client.setAuthenticator(AuthenticatorAdapter.INSTANCE);
    client.setConnectionPool(ConnectionPool.getDefault());
    client.setProtocols(Util.immutableList(Protocol.HTTP_1_1));
    client.setConnectionSpecs(DEFAULT_CONNECTION_SPECS);
    client.setSocketFactory(SocketFactory.getDefault());
    Internal.instance.setNetwork(client, Network.DEFAULT);

    return client;
}
 
Example 5
Source File: RemoteService.java    From AndroidNetwork with MIT License 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();

        //设置超时时间
        //参见:OkHttp3超时设置和超时异常捕获
        //http://blog.csdn.net/do168/article/details/51848895
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
    }
    return service;
}
 
Example 6
Source File: RepoManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static OkHttpClient provideOkHttpClient(Credentials credentials, Context context) {

        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(provideInterceptor(credentials));
        client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        client.setCache(provideCache(context));
        return client;
    }
 
Example 7
Source File: WXOkHttpDispatcher.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 5 votes vote down vote up
private static OkHttpClient defaultOkHttpClient() {
  OkHttpClient client = new OkHttpClient();
  client.networkInterceptors().add(new OkHttpInterceptor());
  client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setReadTimeout(DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  client.setWriteTimeout(DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  return client;
}
 
Example 8
Source File: DataModule.java    From githot with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
OkHttpClient provideOkHttp(Cache cache) {
    OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setCache(cache);
    okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
    return okHttpClient;
}
 
Example 9
Source File: BuildService.java    From Gank with Apache License 2.0 5 votes vote down vote up
public static OkHttpClient defaultOkHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(5 , TimeUnit.SECONDS);
    client.setReadTimeout(5    , TimeUnit.SECONDS);
    client.setWriteTimeout(10  , TimeUnit.SECONDS);
    return client;
}
 
Example 10
Source File: MirrorApplication.java    From mirror with Apache License 2.0 5 votes vote down vote up
private void initializeOkHttp() {
    Cache cache = new Cache(new File(getCacheDir(), "http"), 25 * 1024 * 1024);

    mOkHttpClient = new OkHttpClient();
    mOkHttpClient.setCache(cache);
    mOkHttpClient.setConnectTimeout(30, SECONDS);
    mOkHttpClient.setReadTimeout(30, SECONDS);
    mOkHttpClient.setWriteTimeout(30, SECONDS);
}
 
Example 11
Source File: RemoteService.java    From AndroidNetwork with MIT License 5 votes vote down vote up
public static synchronized RemoteService getInstance() {
    if (service == null) {
        service = new RemoteService();
        mOkHttpClient = new OkHttpClient();

        //设置超时时间
        //参见:OkHttp3超时设置和超时异常捕获
        //http://blog.csdn.net/do168/article/details/51848895
        mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
    }
    return service;
}
 
Example 12
Source File: ApiFactory.java    From spark-sdk-android with Apache License 2.0 5 votes vote down vote up
private static OkHttpClient buildClientWithTimeout(int timeoutInSeconds) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setReadTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setWriteTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    return client;
}
 
Example 13
Source File: NightscoutUploader.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public NightscoutUploader(Context context) {
    mContext = context;
    prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    client = new OkHttpClient();
    client.setConnectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
    client.setReadTimeout(SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
    enableRESTUpload = prefs.getBoolean("cloud_storage_api_enable", false);
    enableMongoUpload = prefs.getBoolean("cloud_storage_mongodb_enable", false);
}
 
Example 14
Source File: OkHttpUtil.java    From Pas with Apache License 2.0 5 votes vote down vote up
private OkHttpUtil() {
    mOkHttpClient = new OkHttpClient();
    // mOkHttpClient.networkInterceptors().add(new StethoInterceptor());

    mOkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
    mOkHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
    mOkHttpClient.setReadTimeout(30, TimeUnit.SECONDS);

    gson=new Gson();

    //更新UI线程
    mainHanlder = new Handler(Looper.getMainLooper());

}
 
Example 15
Source File: BaseRetrofitClient.java    From MVPAndroidBootstrap with Apache License 2.0 5 votes vote down vote up
public <T> T initRestAdapter(String ENDPOINT, Class<T>  restInterface, BaseRetryHandler baseRetryHandler) {
    okHttpClient = new OkHttpClient();
    okHttpClient.setCookieHandler(CookieHandler.getDefault());
    okHttpClient.setConnectTimeout(10, TimeUnit.MINUTES);
    connectivityAwareUrlClient.setWrappedClient(new OkClient(okHttpClient));
    connectivityAwareUrlClient.setRetryHandler(baseRetryHandler);

    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ENDPOINT)
            .setClient(connectivityAwareUrlClient)
                    //  .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();
    return restAdapter.create(restInterface);
}
 
Example 16
Source File: ApiFactory.java    From particle-android with Apache License 2.0 5 votes vote down vote up
private static OkHttpClient buildClientWithTimeout(int timeoutInSeconds) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setReadTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    client.setWriteTimeout(timeoutInSeconds, TimeUnit.SECONDS);
    return client;
}
 
Example 17
Source File: OkHttpStack.java    From jus with Apache License 2.0 5 votes vote down vote up
@Override
public NetworkResponse performRequest(Request<?> request, Headers
        additionalHeaders, ByteArrayPool byteArrayPool) throws IOException {

    //clone to be able to set timeouts per call
    OkHttpClient client = this.client.clone();
    client.setConnectTimeout(request.getRetryPolicy().getCurrentConnectTimeout(), TimeUnit
            .MILLISECONDS);
    client.setReadTimeout(request.getRetryPolicy().getCurrentReadTimeout(), TimeUnit
            .MILLISECONDS);
    com.squareup.okhttp.Request okRequest = new com.squareup.okhttp.Request.Builder()
            .url(request.getUrlString())
            .headers(JusOk.okHeaders(request.getHeaders(), additionalHeaders))
            .tag(request.getTag())
            .method(request.getMethod(), JusOk.okBody(request.getNetworkRequest()))
            .build();

    long requestStart = System.nanoTime();

    Response response = client.newCall(okRequest).execute();

    byte[] data = null;
    if (NetworkDispatcher.hasResponseBody(request.getMethod(), response.code())) {
        data = getContentBytes(response.body().source(),
                byteArrayPool, (int) response.body().contentLength());
    } else {
        // Add 0 byte response as a way of honestly representing a
        // no-content request.
        data = new byte[0];
    }
    return new NetworkResponse.Builder()
            .setHeaders(JusOk.jusHeaders(response.headers()))
            .setStatusCode(response.code())
            .setBody(data)
            .setNetworkTimeNs(System.nanoTime() - requestStart)
            .build();
}
 
Example 18
Source File: TimeoutClientProvider.java    From infobip-api-java-client with Apache License 2.0 5 votes vote down vote up
@Override
public Client get() {
	final OkHttpClient okHttpClient = new OkHttpClient();
	okHttpClient.setReadTimeout(configuration.getReadTimeout(), TimeUnit.MILLISECONDS);
	okHttpClient.setConnectTimeout(configuration.getConnectionTimeout(), TimeUnit.MILLISECONDS);
	return new OkClient(okHttpClient);
}
 
Example 19
Source File: WebSocketClientGenerator.java    From hawkular-android-client with Apache License 2.0 4 votes vote down vote up
public WebSocketClientGenerator(Configuration configuration) {
    this.configuration = configuration;

    OkHttpClient httpClient = new OkHttpClient();

    if(configuration.getConnectTimeoutSeconds()!=-1){
        httpClient.setConnectTimeout(configuration.getConnectTimeoutSeconds(), TimeUnit.SECONDS);
    }

    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;
}
 
Example 20
Source File: OkHttpHelper.java    From ImitateTaobaoApp with Apache License 2.0 3 votes vote down vote up
private OkHttpHelper(){

        mHttpClient = new OkHttpClient();

        mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
        mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);

        mGson = new Gson();

        mHandler = new Handler(Looper.getMainLooper()); //主要接受子线程发送的数据, 并用此数据配合主线程
        // 更新UI

    }