日志拦截器类
请求来了,先在这里进行处理,可以得到发请求到得到请求消耗多久的时间
- 作用:可以排查网络请求速度慢的根本原因
- 1.有可能是我们在请求网络时,客户端写了一堆业务逻辑
- 2.有可能是服务器端,写的有问题
- 3.有可能就是网速不给力
class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
//拿到Request对象
Request request = chain.request();
long t1 = System.nanoTime();
System.out.println(" request = " + String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
//拿到Response对象
Response response = chain.proceed(request);
long t2 = System.nanoTime();
//得出请求网络,到得到结果,中间消耗了多长时间
System.out.println("response " + String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
自定义的缓存拦截器
public class CacheInterecepter implements Interceptor {
@Override//参数:连
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response.newBuilder()
//设置缓存标签,及60秒的时长
.header("Cache-Control", "max-age=60")
.build();
}
}
压缩拦截器, .压缩你请求的内容,需要服务器提供支持
class GzipRequestInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), gzip(originalRequest.body()))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override public MediaType contentType() {
return body.contentType();
}
@Override public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}