Search in sources :

Example 61 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project Signal-Android by WhisperSystems.

the class PushServiceSocket method createConnectionClient.

private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns, Optional<SignalProxy> proxy) {
    try {
        TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, null);
        OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager) trustManagers[0]).connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS))).dns(dns.or(Dns.SYSTEM));
        if (proxy.isPresent()) {
            builder.socketFactory(new TlsProxySocketFactory(proxy.get().getHost(), proxy.get().getPort(), dns));
        }
        builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager) trustManagers[0]).connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS))).build();
        builder.connectionPool(new ConnectionPool(5, 45, TimeUnit.SECONDS));
        for (Interceptor interceptor : interceptors) {
            builder.addInterceptor(interceptor);
        }
        return builder.build();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }
}
Also used : ConnectionPool(okhttp3.ConnectionPool) OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) Tls12SocketFactory(org.whispersystems.signalservice.api.util.Tls12SocketFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) X509TrustManager(javax.net.ssl.X509TrustManager) BlacklistingTrustManager(org.whispersystems.signalservice.internal.util.BlacklistingTrustManager) TrustManager(javax.net.ssl.TrustManager) Interceptor(okhttp3.Interceptor) TlsProxySocketFactory(org.whispersystems.signalservice.api.util.TlsProxySocketFactory)

Example 62 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project Signal-Android by WhisperSystems.

the class WebSocketConnection method connect.

public synchronized Observable<WebSocketConnectionState> connect() {
    log("connect()");
    if (client == null) {
        String filledUri;
        if (credentialsProvider.isPresent()) {
            String identifier = Objects.requireNonNull(credentialsProvider.get().getAci()).toString();
            if (credentialsProvider.get().getDeviceId() != SignalServiceAddress.DEFAULT_DEVICE_ID) {
                identifier += "." + credentialsProvider.get().getDeviceId();
            }
            filledUri = String.format(wsUri, identifier, credentialsProvider.get().getPassword());
        } else {
            filledUri = wsUri;
        }
        Pair<SSLSocketFactory, X509TrustManager> socketFactory = createTlsSocketFactory(trustStore);
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder().sslSocketFactory(new Tls12SocketFactory(socketFactory.first()), socketFactory.second()).connectionSpecs(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)).readTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS).dns(dns.or(Dns.SYSTEM)).connectTimeout(KEEPALIVE_TIMEOUT_SECONDS + 10, TimeUnit.SECONDS);
        for (Interceptor interceptor : interceptors) {
            clientBuilder.addInterceptor(interceptor);
        }
        if (signalProxy.isPresent()) {
            clientBuilder.socketFactory(new TlsProxySocketFactory(signalProxy.get().getHost(), signalProxy.get().getPort(), dns));
        }
        OkHttpClient okHttpClient = clientBuilder.build();
        Request.Builder requestBuilder = new Request.Builder().url(filledUri);
        if (signalAgent != null) {
            requestBuilder.addHeader("X-Signal-Agent", signalAgent);
        }
        webSocketState.onNext(WebSocketConnectionState.CONNECTING);
        this.client = okHttpClient.newWebSocket(requestBuilder.build(), this);
    }
    return webSocketState;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) Request(okhttp3.Request) ByteString(okio.ByteString) Tls12SocketFactory(org.whispersystems.signalservice.api.util.Tls12SocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Interceptor(okhttp3.Interceptor) TlsProxySocketFactory(org.whispersystems.signalservice.api.util.TlsProxySocketFactory)

Example 63 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project SeeWeather by xcc3641.

the class RetrofitSingleton method initOkHttp.

private static void initOkHttp() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // 缓存 http://www.jianshu.com/p/93153b34310e
    File cacheFile = new File(C.NET_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = chain -> {
        Request request = chain.request();
        if (!Util.isNetworkConnected(BaseApplication.getAppContext())) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        Response.Builder newBuilder = response.newBuilder();
        if (Util.isNetworkConnected(BaseApplication.getAppContext())) {
            int maxAge = 0;
            // 有网络时 设置缓存超时时间0个小时
            newBuilder.header("Cache-Control", "public, max-age=" + maxAge);
        } else {
            // 无网络时,设置超时为4周
            int maxStale = 60 * 60 * 24 * 28;
            newBuilder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale);
        }
        return newBuilder.build();
    };
    builder.cache(cache).addInterceptor(cacheInterceptor);
    if (BuildConfig.DEBUG) {
        builder.addNetworkInterceptor(new StethoInterceptor());
    }
    // 设置超时
    builder.connectTimeout(15, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    // 错误重连
    builder.retryOnConnectionFailure(true);
    sOkHttpClient = builder.build();
}
Also used : StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) BaseApplication(com.xiecc.seeWeather.base.BaseApplication) C(com.xiecc.seeWeather.common.C) CacheControl(okhttp3.CacheControl) Consumer(io.reactivex.functions.Consumer) CityORM(com.xiecc.seeWeather.modules.main.domain.CityORM) File(java.io.File) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) BuildConfig(com.xiecc.seeWeather.BuildConfig) TimeUnit(java.util.concurrent.TimeUnit) ToastUtil(com.xiecc.seeWeather.common.utils.ToastUtil) OkHttpClient(okhttp3.OkHttpClient) Util(com.xiecc.seeWeather.common.utils.Util) RxUtil(com.xiecc.seeWeather.common.utils.RxUtil) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Version(com.xiecc.seeWeather.modules.about.domain.Version) Response(okhttp3.Response) Observable(io.reactivex.Observable) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Weather(com.xiecc.seeWeather.modules.main.domain.Weather) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) WhereBuilder(com.litesuits.orm.db.assit.WhereBuilder) Request(okhttp3.Request) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) File(java.io.File) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Interceptor(okhttp3.Interceptor) Cache(okhttp3.Cache)

Example 64 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project OkHttp3 by MrZhousf.

the class DownUpLoadHelper method downloadFile.

/**
 * 文件下载
 */
void downloadFile(final OkHttpHelper helper) {
    try {
        final HttpInfo info = httpInfo;
        final DownloadFileInfo fileInfo = helper.getDownloadFileInfo();
        String url = fileInfo.getUrl();
        if (TextUtils.isEmpty(url)) {
            showLog("下载文件失败:文件下载地址不能为空!");
            return;
        }
        info.setUrl(url);
        ProgressCallback progressCallback = fileInfo.getProgressCallback();
        // 获取文件断点
        long completedSize = fetchCompletedSize(fileInfo);
        fileInfo.setCompletedSize(completedSize);
        // 添加下载任务
        if (null == downloadTaskMap)
            downloadTaskMap = new ConcurrentHashMap<>();
        if (downloadTaskMap.containsKey(fileInfo.getSaveFileNameEncrypt())) {
            showLog(fileInfo.getSaveFileName() + " 已在下载任务中");
            return;
        }
        downloadTaskMap.put(fileInfo.getSaveFileNameEncrypt(), fileInfo.getSaveFileNameEncrypt());
        Interceptor interceptor = new Interceptor() {

            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder().body(new ProgressResponseBody(originalResponse.body(), fileInfo, timeStamp, requestTag)).build();
            }
        };
        try {
            // 采用新的OkHttpClient处理多线程干扰回调进度问题
            OkHttpClient httpClient = super.clientBuilder.addInterceptor(interceptor).build();
            Request.Builder requestBuilder = new Request.Builder();
            requestBuilder.url(url).header("RANGE", "bytes=" + completedSize + "-");
            addHeadsToRequest(info, requestBuilder);
            Request request = requestBuilder.build();
            helper.setRequest(request);
            helper.setHttpClient(httpClient);
            responseCallback(helper.doRequestSync(), progressCallback, OkMainHandler.RESPONSE_DOWNLOAD_CALLBACK, requestTag);
        } finally {
            // 删除下载任务
            if (null != downloadTaskMap) {
                downloadTaskMap.remove(fileInfo.getSaveFileNameEncrypt());
            }
        }
    } catch (Exception e) {
        showLog("下载文件失败:" + e.getMessage());
    }
}
Also used : DownloadFileInfo(com.okhttplib.bean.DownloadFileInfo) OkHttpClient(okhttp3.OkHttpClient) ProgressCallback(com.okhttplib.callback.ProgressCallback) Request(okhttp3.Request) ProgressResponseBody(com.okhttplib.progress.ProgressResponseBody) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) HttpInfo(com.okhttplib.HttpInfo) Response(okhttp3.Response) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Interceptor(okhttp3.Interceptor)

Example 65 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project keywhiz by square.

the class HttpClients method testSslClient.

/**
 * Create a {@link OkHttpClient} for tests.
 *
 * @param keyStore Use a client certificate from keystore if present. Client certs disabled if null.
 * @param keyStorePassword keyStore password. Client certs disabled if null.
 * @param requestInterceptors Any request interceptors to register with client.
 * @return new http client
 */
private static OkHttpClient testSslClient(@Nullable KeyStore keyStore, @Nullable String keyStorePassword, KeyStore trustStore, List<Interceptor> requestInterceptors) {
    boolean usingClientCert = keyStore != null && keyStorePassword != null;
    SSLContext sslContext;
    X509TrustManager trustManager;
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder().useProtocol("TLSv1.2").loadTrustMaterial(trustStore);
        if (usingClientCert) {
            sslContextBuilder.loadKeyMaterial(keyStore, keyStorePassword.toCharArray());
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        trustManager = (X509TrustManager) trustManagers[0];
        sslContext = sslContextBuilder.build();
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw Throwables.propagate(e);
    }
    OkHttpClient.Builder client = new OkHttpClient().newBuilder().sslSocketFactory(sslContext.getSocketFactory(), trustManager).connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).followSslRedirects(false);
    client.followRedirects(false);
    client.retryOnConnectionFailure(false);
    // Won't use cookies and a client certificate at once.
    if (!usingClientCert) {
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.cookieJar(new JavaNetCookieJar(cookieManager));
    }
    for (Interceptor interceptor : requestInterceptors) {
        client.networkInterceptors().add(interceptor);
    }
    return client.build();
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) UnrecoverableKeyException(java.security.UnrecoverableKeyException) X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) Interceptor(okhttp3.Interceptor) CookieManager(java.net.CookieManager)

Aggregations

Interceptor (okhttp3.Interceptor)138 Request (okhttp3.Request)61 OkHttpClient (okhttp3.OkHttpClient)54 Response (okhttp3.Response)51 IOException (java.io.IOException)45 Test (org.junit.Test)29 Retrofit (retrofit2.Retrofit)27 File (java.io.File)15 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)13 Cache (okhttp3.Cache)9 HttpUrl (okhttp3.HttpUrl)8 Interceptor (com.pushtorefresh.storio3.Interceptor)7 Dispatcher (okhttp3.Dispatcher)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 X509TrustManager (javax.net.ssl.X509TrustManager)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)5 Provides (dagger.Provides)5 Singleton (javax.inject.Singleton)5 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)5 OAuth (com.arm.mbed.cloud.sdk.internal.devicedirectory.auth.OAuth)4