【Android】三种拦截器

日志拦截器类
请求来了,先在这里进行处理,可以得到发请求到得到请求消耗多久的时间

  • 作用:可以排查网络请求速度慢的根本原因
  • 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();
      }
    };
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值