澳门皇冠金沙网站-澳门皇冠844网站

热门关键词: 澳门皇冠金沙网站,澳门皇冠844网站

Okhttp-wiki 之 Interceptors 拦截器

Registering a network interceptor is quite similar. Call addNetworkInterceptor() instead of addInterceptor():

Interceptors

Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Here's a simple interceptor that logs the outgoing request and the incoming response.

皇冠资讯下载 1

application 拦截器,下面一个栗子会说明;

插入器是一个很有用技巧 ,可以监控,重写和重新请求。下面举个栗子, 拦截器日志优于请求和即将到来响应;

A call to chain.proceed(request)is a critical part of each interceptor’s implementation. This simple-looking method is where all the HTTP work happens, producing a response to satisfy the request.Interceptors can be chained. Suppose you have both a compressing interceptor and a check summing interceptor: you'll need to decide whether data is compressed and then checksummed, or checksummed and then compressed. OkHttp uses lists to track interceptors, and interceptors are called in order.

一个请求 chain.proceed(request) 是一个临界的拦截器实现的部分,它简单可见的方法是对所有Http线程发生,生产响应对满意的请求,拦截器可以被束缚,支持你所有压缩拦截和求和拦截,你将需要决定是数据压缩然后检验,或者检验和再压缩。okhttp使用Lists集合去追踪拦截器,拦截器顺便被调用;

皇冠资讯下载 2

网络请求 监听请求信息以及相应头信息

Interceptors are registered as either application or network interceptors. We'll use theLoggingInterceptor defined above to show the difference.

Register anapplication interceptor by calling addInterceptor() onOkHttpClient.Builder:

拦截器注册既不是应用也非网络拦截器,我们将使用这个LoggingInterceptor定义显示不同之处,注册在Application拦截器 通过调用addInterceptor方法在okHttpClient.Builder;

皇冠资讯下载 3

构建okHttpClient实例对象,添加拦截器

执行结果: 

皇冠资讯下载 4

执行结果当中,url重定向了,共花费3s多

Rewriting Responses 重写响应

If transparent compression was used, OkHttp will drop the corresponding response headers Content-Encoding and Content-Length because they don’t apply to the decompressed response body.

如果使用了明确的压缩,OkHttp将删除对应的响应头信息:内容编码和内容长度,因为他们并不适用于实体解压的响应实体。

If a conditional GET was successful, responses from the network and cache are merged as directed by the spec.

如果GET请求成功,响应和缓存将会按照规范来合并.

当我们运行这段代码时,拦截器运行两次.第一次是初始化请求到 http://www.publicobject.com/helloworld.txt的时候调用,另一个用于重定向到 https://publicobject.com/helloworld.txt的时候.

Follow-up Requests 跟进请求

When your requested URL has moved, the webserver will return a response code like 302 to indicate the document’s new URL. OkHttp will follow the redirect to retrieve a final response.

当你通过URL请求时,网络服务器将返回一个响应代码,比如说302来指出新的URL路径.OkHttp会重定向直到检索到最终的响应。

If the response issues an authorization challenge, OkHttp will ask the Authenticator (if one is configured) to satisfy the challenge. If the authenticator supplies a credential, the request is retried with that credential included.

如果响应需要授权验证,OkHttp将访问Authenticator(如果已经配置过一个)来满足这个验证。如果认证器提供一个凭证,请求将会带上凭证重新访问。

Interceptors can be chained. Suppose you have both a compressing interceptor and a checksumming interceptor: you'll need to decide whether data is compressed and then checksummed, or checksummed and then compressed. OkHttp uses lists to track interceptors, and interceptors are called in order.

The HTTP client’s job is to accept your request and produce its response. This is simple in theory but it gets tricky in practice.

The URL http://www.publicobject.com/helloworld.txt redirects to https://publicobject.com/helloworld.txt, and OkHttp follows this redirect automatically. Our application interceptor is called once and the response returned from chain.proceed() has the redirected response:

Calls 调用

With rewrites, redirects, follow-ups and retries, your simple request may yield many requests and responses. OkHttp uses Call to model the task of satisfying your request through however many intermediate requests and responses are necessary. Typically this isn’t many! But it’s comforting to know that your code will continue to work if your URLs are redirected or if you failover to an alternate IP address.

伴随着重写,重定向,跟进和重试,你简单的请求可能产生许多请求和响应。OkHttp将调用一系列任务直到满足你的需求,然而许多中间的任务请求和响应是必要的。通常这不是很多!但欣慰的是您的代码将继续执行如果你的url重定向或故障转移到另一个IP地址。

Calls are executed in one of two ways:

  • Synchronous: your thread blocks until the response is readable.
  • Asynchronous: you enqueue the request on any thread, and get called back on another thread when the response is readable.

调用将会执行以下两种方式中的一种:

  • 同步的:你的线程被锁住直到响应返回.
  • 异步的:你在任何线程安排请求,在另一个线程获得响应回调。

Calls can be canceled from any thread. This will fail the call if it hasn’t yet completed皇冠赌场,! Code that is writing the request body or reading the response body will suffer an IOException when its call is canceled.

皇冠资讯下载,从任何线程都可以取消调用。如果调用还没有完成,这将使得调用失败!当调用取消时代码中对请求实体或响应实体做读写操作会得到一个IOException。

We can see that we were redirected because response.request皇冠国际娱乐, is different from request.url(). The two log statements log two different URLs.

Dispatch 派遣

For synchronous calls, you bring your own thread and are responsible for managing how many simultaneous requests you make. Too many simultaneous connections wastes resources; too few harms latency.

对于同步调用,你用自己的线程负责管理有多少并发请求。太多的并发连接浪费资源;特别是导致延迟。

For asynchronous calls, Dispatcher implements policy for maximum simultaneous requests. You can set maximums per-webserver (default is 5), and overall (default is 64).

对于异步调用,Dispatcher实现最多的并发请求政策。你可以设置每个主机最大请求数(默认为5),和最大并发请求数(默认是64)。


对OkHttp感兴趣的朋友可以看一看Okhttp-wiki系列,可以帮助你理解Okhttp的使用方法及原理:

  1. Okhttp-wiki 之 Home 主页
  2. Okhttp-wiki 之 Calls 调用
  3. Okhttp-wiki 之 Connections 连接
  4. Okhttp-wiki 之 Recipes 秘诀(食谱)
  5. Okhttp-wiki 之 Interceptors 拦截器
  6. Okhttp-wiki 之 HTTPS

每个拦截器链都有自己的优点.

Rewriting Requests 重写请求

When you provide OkHttp with an HTTP request, you’re describing the request at a high-level: “fetch me this URL with these headers.” For correctness and efficiency, OkHttp rewrites your request before transmitting it.

为OkHttp提供一个HTTP请求时,你描述一个高水平的请求给okhttp:"拿到包含这些头信息的请求".为了确保正确性和效率,在传输之前OkHttp会重写你的请求。

OkHttp may add headers that are absent from the original request, including Content-Length, Transfer-Encoding, User-Agent, Host, Connection, and Content-Type. It will add an Accept-Encoding header for transparent response compression unless the header is already present. If you’ve got cookies, OkHttp will add a Cookie header with them.

OkHttp可能为原始请求添加缺少的头信息,包括内容长度,传输编码,用户代理、主机,连接,和内容类型。它将添加一个明确的编码头信息来压缩响应,除非该头信息已经存在.如果你有cookies,OkHttp将添加一个cookie头信息在里面。

Some requests will have a cached response. When this cached response isn’t fresh, OkHttp can do a conditional GET to download an updated response if it’s newer than what’s cached. This requires headers like If-Modified-Since and If-None-Match to be added.

一些请求会有响应的缓存。当这个缓存的响应不再是最新的,OkHttp做一个条件判断如果有新的响应则下载最新的响应.这种需求头信息被添加就像If-Modified-Since 和 If-None-Match模式。(如果没有缓存则匹配最新的并缓存下来;如果有缓存则看看是否是最新的,如果是最新的则直接返回缓存,否则请求最新的并更新缓存.)

Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Here's a simple interceptor that logs the outgoing request and the incoming response.

Requests 请求

Each HTTP request contains a URL, a method (like GET or POST), and a list of headers. Requests may also contain a body: a data stream of a specific content type.

每个HTTP请求包含一个URL、一个方法(如GET或POST),同时包含头信息的列表。请求也可能包含一个实体:具体类型内容的数据流。

Interceptors are registered as either application or network interceptors. We'll use the LoggingInterceptor defined above to show the difference.

HTTP客户端的工作是接受你的请求,并生成其响应。说起来简单但做起来复杂.

Each interceptor chain has relative merits.

Retrying Requests 请求重试

Sometimes connections fail: either a pooled connection was stale and disconnected, or the webserver itself couldn’t be reached. OkHttp will retry the request with a different route if one is available.

有时候会连接失败:某个连接池过时了或者断开连接,或者该网络服务器本身无法被访问。OkHttp将通过一个不同的线路重试请求。

拦截器可以被应用程序或网络注册,我们将使用上面定义的 LoggingInterceptor 显示两者之间的差异.

Responses 响应

The response answers the request with a code (like 200 for success or 404 for not found), headers, and its own optional body.

根据请求返回的响应码(成功的200或没有找到内容的404),头信息,和可选的实体。

OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new LoggingInterceptor .build();Request request = new Request.Builder() .url("http://www.publicobject.com/helloworld.txt") .header("User-Agent", "OkHttp Example") .build();Response response = client.newCall.execute();response.body;

本文由澳门皇冠金沙网站发布于编辑程序,转载请注明出处:Okhttp-wiki 之 Interceptors 拦截器