use of com.pushtorefresh.storio3.Interceptor in project apollo-android by apollographql.
the class ApolloPrefetchTest method setup.
@Before
public void setup() {
cacheStore = new MockHttpCacheStore();
cacheStore.delegate = new DiskLruHttpCacheStore(inMemoryFileSystem, new File("/cache/"), Integer.MAX_VALUE);
okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
lastHttRequest = chain.request();
lastHttResponse = chain.proceed(lastHttRequest);
return lastHttResponse;
}
}).dispatcher(new Dispatcher(Utils.immediateExecutorService())).build();
apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).dispatcher(Utils.immediateExecutor()).httpCache(new ApolloHttpCache(cacheStore, null)).build();
}
use of com.pushtorefresh.storio3.Interceptor in project Fast-Android-Networking by amitshekhariitbhu.
the class InternalNetworking method performDownloadRequest.
public static Response performDownloadRequest(final ANRequest request) throws ANError {
Request okHttpRequest;
Response okHttpResponse;
try {
Request.Builder builder = new Request.Builder().url(request.getUrl());
addHeadersToRequestBuilder(builder, request);
builder = builder.get();
if (request.getCacheControl() != null) {
builder.cacheControl(request.getCacheControl());
}
okHttpRequest = builder.build();
OkHttpClient okHttpClient;
if (request.getOkHttpClient() != null) {
okHttpClient = request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
}
}).build();
} else {
okHttpClient = sHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
}
}).build();
}
request.setCall(okHttpClient.newCall(okHttpRequest));
final long startTime = System.currentTimeMillis();
final long startBytes = TrafficStats.getTotalRxBytes();
okHttpResponse = request.getCall().execute();
Utils.saveFile(okHttpResponse, request.getDirPath(), request.getFileName());
final long timeTaken = System.currentTimeMillis() - startTime;
if (okHttpResponse.cacheResponse() == null) {
final long finalBytes = TrafficStats.getTotalRxBytes();
final long diffBytes;
if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
diffBytes = okHttpResponse.body().contentLength();
} else {
diffBytes = finalBytes - startBytes;
}
ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, okHttpResponse.body().contentLength(), false);
} else if (request.getAnalyticsListener() != null) {
Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, 0, true);
}
} catch (IOException ioe) {
try {
File destinationFile = new File(request.getDirPath() + File.separator + request.getFileName());
if (destinationFile.exists()) {
destinationFile.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
throw new ANError(ioe);
}
return okHttpResponse;
}
use of com.pushtorefresh.storio3.Interceptor in project Fast-Android-Networking by amitshekhariitbhu.
the class RxInternalNetworking method generateDownloadObservable.
public static <T> Observable<T> generateDownloadObservable(final RxANRequest request) {
Request okHttpRequest;
Request.Builder builder = new Request.Builder().url(request.getUrl());
InternalNetworking.addHeadersToRequestBuilder(builder, request);
builder = builder.get();
if (request.getCacheControl() != null) {
builder.cacheControl(request.getCacheControl());
}
okHttpRequest = builder.build();
OkHttpClient okHttpClient;
if (request.getOkHttpClient() != null) {
okHttpClient = request.getOkHttpClient().newBuilder().cache(InternalNetworking.sHttpClient.cache()).addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
}
}).build();
} else {
okHttpClient = InternalNetworking.sHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
}
}).build();
}
request.setCall(okHttpClient.newCall(okHttpRequest));
return Observable.create(new ANOnSubscribe<T>(request));
}
use of com.pushtorefresh.storio3.Interceptor in project drill by apache.
the class SimpleHttp method setupHttpClient.
/**
* Configures the OkHTTP3 server object with configuration info from the user.
*
* @return OkHttpClient configured server
*/
private OkHttpClient setupHttpClient() {
Builder builder = new OkHttpClient.Builder();
// Set up the HTTP Cache. Future possibilities include making the cache size and retention configurable but
// right now it is on or off. The writer will write to the Drill temp directory if it is accessible and
// output a warning if not.
HttpStoragePluginConfig config = scanDefn.tableSpec().config();
if (config.cacheResults()) {
setupCache(builder);
}
HttpApiConfig apiConfig = scanDefn.tableSpec().connectionConfig();
// If OAuth information is provided, we will assume that the user does not want to use
// basic authentication
HttpOAuthConfig oAuthConfig = scanDefn.tableSpec().config().oAuthConfig();
if (oAuthConfig != null) {
// Add interceptors for OAuth2
logger.debug("Adding OAuth2 Interceptor");
AccessTokenRepository repository = new AccessTokenRepository(proxyConfig, config, tokenTable);
builder.authenticator(new AccessTokenAuthenticator(repository));
builder.addInterceptor(new AccessTokenInterceptor(repository));
} else if (apiConfig.authType().equalsIgnoreCase("basic")) {
// If the API uses basic authentication add the authentication code.
logger.debug("Adding Interceptor");
UsernamePasswordCredentials credentials = apiConfig.getUsernamePasswordCredentials();
builder.addInterceptor(new BasicAuthInterceptor(credentials.getUsername(), credentials.getPassword()));
}
// Set timeouts
int timeout = Math.max(1, config.timeout());
builder.connectTimeout(timeout, TimeUnit.SECONDS);
builder.writeTimeout(timeout, TimeUnit.SECONDS);
builder.readTimeout(timeout, TimeUnit.SECONDS);
// Sourced from https://stackoverflow.com/questions/60110848/how-to-disable-ssl-verification
if (!apiConfig.verifySSLCert()) {
try {
TrustManager[] trustAllCerts = getAllTrustingTrustManager();
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
HostnameVerifier verifier = (hostname, session) -> true;
builder.hostnameVerifier(verifier);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
logger.error("Error when configuring Drill not to verify SSL certs. {}", e.getMessage());
}
}
// Set the proxy configuration
addProxyInfo(builder, proxyConfig);
return builder.build();
}
use of com.pushtorefresh.storio3.Interceptor in project GeekNews by codeestX.
the class HttpModule method provideClient.
@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(loggingInterceptor);
}
File cacheFile = new File(Constants.PATH_CACHE);
Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
Interceptor cacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!SystemUtil.isNetworkConnected()) {
request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
}
Response response = chain.proceed(request);
if (SystemUtil.isNetworkConnected()) {
int maxAge = 0;
// 有网络时, 不缓存, 最大保存时长为0
response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
} else {
// 无网络时,设置超时为4周
int maxStale = 60 * 60 * 24 * 28;
response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
}
return response;
}
};
// Interceptor apikey = new Interceptor() {
// @Override
// public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();
// request = request.newBuilder()
// .addHeader("apikey",Constants.KEY_API)
// .build();
// return chain.proceed(request);
// }
// }
// 设置统一的请求头部参数
// builder.addInterceptor(apikey);
// 设置缓存
builder.addNetworkInterceptor(cacheInterceptor);
builder.addInterceptor(cacheInterceptor);
builder.cache(cache);
// 设置超时
builder.connectTimeout(10, TimeUnit.SECONDS);
builder.readTimeout(20, TimeUnit.SECONDS);
builder.writeTimeout(20, TimeUnit.SECONDS);
// 错误重连
builder.retryOnConnectionFailure(true);
return builder.build();
}
Aggregations