use of okhttp3.Interceptor in project okhttp by square.
the class WebSocketHttpTest method webSocketAndNetworkInterceptors.
@Test
public void webSocketAndNetworkInterceptors() throws IOException {
client = client.newBuilder().addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// Network interceptors don't execute.
throw new AssertionError();
}
}).build();
webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
WebSocket webSocket = newWebSocket();
clientListener.assertOpen();
webSocket.close(1000, null);
WebSocket server = serverListener.assertOpen();
server.close(1000, null);
}
use of okhttp3.Interceptor in project okhttp by square.
the class OkHttpURLConnection method connect.
@Override
public void connect() throws IOException {
if (executed)
return;
Call call = buildCall();
executed = true;
call.enqueue(this);
synchronized (lock) {
try {
while (connectPending && response == null && callFailure == null) {
// Wait 'til the network interceptor is reached or the call fails.
lock.wait();
}
if (callFailure != null) {
throw propagate(callFailure);
}
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
use of okhttp3.Interceptor in project okhttp by square.
the class WebSocketHttpTest method webSocketAndApplicationInterceptors.
@Test
public void webSocketAndApplicationInterceptors() throws IOException {
final AtomicInteger interceptedCount = new AtomicInteger();
client = client.newBuilder().addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
assertNull(chain.request().body());
Response response = chain.proceed(chain.request());
assertEquals("Upgrade", response.header("Connection"));
assertTrue("", response.body().source().exhausted());
interceptedCount.incrementAndGet();
return response;
}
}).build();
webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
WebSocket webSocket = newWebSocket();
clientListener.assertOpen();
assertEquals(1, interceptedCount.get());
webSocket.close(1000, null);
WebSocket server = serverListener.assertOpen();
server.close(1000, null);
}
use of okhttp3.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 okhttp3.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