okhttp日志拦截器+缓存

//GlobalConfiguration

                //okhttpBuilder.writeTimeout(10, TimeUnit.SECONDS);
                File cacheFile = new File(context.getExternalCacheDir(),"tangnuer");
                Cache cache = new Cache(cacheFile,1024*1024*50);
                okhttpBuilder
                        .cache(cache)
                        .addNetworkInterceptor(new HttpCaCheInterceper())
                        .addInterceptor(new LoggingInterceptor())
                        .build();

//缓存类
private class HttpCaCheInterceper implements Interceptor{
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Response response = chain.proceed(request);
        //无网络缓存到本地,保存时间(30天)
        Response response1 = response.newBuilder()
                .removeHeader("Pragma")
                .removeHeader("Cache-Control")
                .header("Cache-Control", "max-age=" + 3600 * 24 * 30)
                .build();
        return response1;
    }
}

//日志拦截器类
public class LoggingInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {

    Request request = chain.request();
    long t1 = System.nanoTime();//请求发起的时间
    String method = request.method();
    StringBuilder sb = new StringBuilder();
    RequestBody body = request.body();
    Response response = chain.proceed(request);
//        LogUtils.e("pwjrequest", request.headers() + "" + request.url() + "");
    long t2 = System.nanoTime();//收到响应的时间
    //这里不能直接使用response.body().string()的方式输出日志
    //因为response.body().string()之后,response中的流会被关闭,程序会报错,我们需要创建出一 个新的response给应用层处理
    ResponseBody responseBody = response.peekBody(1024 * 1024);
    LogUtils.e(String.format("发送请求 %s on %s %n%s %nRequestParams:{%s}",
            request.url(), chain.connection(), request.headers(), response.toString()));
    return response;
    //这个chain里面包含了request和response,所以你要什么都可以从这里拿

}

你可能感兴趣的:(okhttp日志拦截器+缓存)