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);
}
}
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;
}
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();
}
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());
}
}
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();
}
Aggregations