OkHttp Wiki翻译(五)拦截器


原文:https://github.com/square/okhttp/wiki/Interceptors

下面是翻译: 



拦截器

拦截器是一种强大的机制,可以监视,重写和重试请求。 下面是一个简单的拦截器,用于记录传出的请求和传入的响应。

class LoggingInterceptorimplements Interceptor

{

    @Override public Responseintercept(Interceptor.Chain chain) throws IOException

    {

        Request request = chain.request();

 

        long t1 = System.nanoTime();

        logger.info(String.format("Sendingrequest %s on %s%n%s",

                                 request.url(), chain.connection(), request.headers()));

 

        Response response =chain.proceed(request);

 

        long t2 = System.nanoTime();

       logger.info(String.format("Received response for %s in%.1fms%n%s",

                                 response.request().url(), (t2 - t1) / 1e6d, response.headers()));

 

        return response;

    }

}

 

对chain.proceed(request)的调用是每个拦截器实现的关键部分。 这个简单的方法是所有HTTP工作发生的地方,用于产生满足请求的响应。

 

拦截器可以链式调用。 假设您同时拥有一个压缩拦截器和一个校验和拦截器:您需要确定数据是否已压缩,然后进行校验和,或先进行校验和然后再压缩。 OkHttp使用列表来跟踪拦截器,拦截器按顺序调用。

 

 

应用拦截器

拦截器被注册为应用程序或网络拦截器。 我们将使用上面定义的LoggingInterceptor来显示差异。

 

通过在OkHttpClient.Builder上调用Interceptor()来注册应用程序拦截器:

OkHttpClient client = newOkHttpClient.Builder()

.addInterceptor(newLoggingInterceptor())

.build();

 

Request request = newRequest.Builder()

.url("http://www.publicobject.com/helloworld.txt")

.header("User-Agent","OkHttp Example")

.build();

 

Response response =client.newCall(request).execute();

response.body().close();

 

URLhttp://www.publicobject.com/helloworld.txt重定向到https://publicobject.com/helloworld.txt,OkHttp自动遵循此重定向。我们的应用拦截器被调用一次,从chain.proceed()返回的响应具有重定向的响应:

 

INFO: Sending requesthttp://www.publicobject.com/helloworld.txt on null

User-Agent: OkHttp Example

 

INFO: Received response forhttps://publicobject.com/helloworld.txt in 1179.7ms

Server: nginx/1.4.6 (Ubuntu)

Content-Type: text/plain

Content-Length: 1759

Connection: keep-alive

 

我们可以看到我们被重定向了,因为response.request().url()与request.url()不同。 两个日志语句记录两个不同的URL。

 

网络拦截器

注册网络拦截器是非常相似的。 调用addNetworkInterceptor()而不是addInterceptor():

OkHttpClient client = newOkHttpClient.Builder()

.addNetworkInterceptor(newLoggingInterceptor())

.build();

 

Request request = newRequest.Builder()

.url("http://www.publicobject.com/helloworld.txt")

.header("User-Agent","OkHttp Example")

.build();

 

Response response =client.newCall(request).execute();

response.body().close();

 

当我们运行这个代码时,拦截器运行两次。 一次为初始请求http://www.publicobject.com/helloworld.txt,另一个为重定向到https://publicobject.com/helloworld.txt。

 

INFO: Sending requesthttp://www.publicobject.com/helloworld.txt on Connection{www.publicobject.com:80,proxy=DIRECT hostAddress=54.187.32.157 cipherSuite=none protocol=http/1.1}

User-Agent: OkHttp Example

Host: www.publicobject.com

Connection: Keep-Alive

Accept-Encoding: gzip

 

INFO: Received response forhttp://www.publicobject.com/helloworld.txt in 115.6ms

Server: nginx/1.4.6 (Ubuntu)

Content-Type: text/html

Content-Length: 193

Connection: keep-alive

Location:https://publicobject.com/helloworld.txt

 

INFO: Sending requesthttps://publicobject.com/helloworld.txt on Connection{publicobject.com:443,proxy=DIRECT hostAddress=54.187.32.157cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1}

User-Agent: OkHttp Example

Host: publicobject.com

Connection: Keep-Alive

Accept-Encoding: gzip

 

INFO: Received response forhttps://publicobject.com/helloworld.txt in 80.9ms

Server: nginx/1.4.6 (Ubuntu)

Content-Type: text/plain

Content-Length: 1759

Connection: keep-alive

 

网络请求还包含更多的数据,例如由OkHttp添加的Accept-Encoding:gzip头来标志支持响应压缩。 网络拦截器的链路具有非空连接,可用于询问用于连接到Web服务器的IP地址和TLS配置。

 

 

在应用和网络拦截器之间进行选择

每个拦截链都有其优点。

 

应用拦截器

不需要担心中间响应,如重定向和重试。

总是调用一次,即使从缓存提供HTTP响应。

遵守应用程序的原始意图。 不关心OkHttp注入的请求头,如If-None-Match。

允许短路,不调用Chain.proceed()。

允许重试并多次调用Chain.proceed()。

 

网络拦截器

能够对重定向和重试等中间响应进行操作。

不调用缓存的响应来短路网络。

观察数据,就像通过网络传输一样。

访问携带请求的Connection。

 

 

重写请求

拦截器可以添加,删除或替换请求头。 他们还可以转换具有一个请求的正文。 例如,如果您连接到已知支持它的Web服务器,则可以使用应用程序拦截器添加压缩的请求体。

/** This interceptorcompresses the HTTP request body. Many webservers can't handle this! */

final classGzipRequestInterceptor implements Interceptor

{

    @Override public Responseintercept(Interceptor.Chain chain) throws IOException

    {

        Request originalRequest =chain.request();

        if (originalRequest.body() == null ||originalRequest.header("Content-Encoding") != null)

        {

            returnchain.proceed(originalRequest);

        }

 

        Request compressedRequest =originalRequest.newBuilder()

                                   .header("Content-Encoding", "gzip")

                                    .method(originalRequest.method(),gzip(originalRequest.body()))

                                    .build();

        returnchain.proceed(compressedRequest);

    }

 

    private RequestBody gzip(final RequestBodybody)

    {

        return new RequestBody()

        {

            @Override public MediaTypecontentType()

            {

                return body.contentType();

            }

 

            @Override public longcontentLength()

            {

                return -1; // We don't know thecompressed length in advance!

            }

 

            @Override public voidwriteTo(BufferedSink sink) throws IOException

            {

                BufferedSink gzipSink =Okio.buffer(new GzipSink(sink));

                body.writeTo(gzipSink);

                gzipSink.close();

            }

        };

    }

}

 

重写响应

对称地,拦截器可以重写响应头并转换响应体。 这通常比重写请求头更危险,因为它可能违反了网络服务器的期望!

 

如果您处于棘手的情况,并准备应对后果,重写响应头是解决问题的有效方式。 例如,您可以修复服务器配置错误的Cache-Control响应头,以实现更好的响应缓存:

/** Dangerous interceptorthat rewrites the server's cache-control header. */

private static finalInterceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor()

{

    @Override public Responseintercept(Interceptor.Chain chain) throws IOException

    {

        Response originalResponse =chain.proceed(chain.request());

        return originalResponse.newBuilder()

              .header("Cache-Control", "max-age=60")

               .build();

    }

};

 

通常,这种方法在补充Web服务器上的相应修复程序时效果最好!

 

 

可用性

OkHttp拦截器需要OkHttp 2.2或更高版本。 不幸的是,拦截器不能与OkUrlFactory或其上构建的库一起使用,包括Retrofit≤1.8和Picasso≤2.4。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值