OkHttp 上手

OkHttp 上手

优点

  1. 快、节省带宽。
  2. 支持 HTTP/2 和 SPDY。
  3. HTTP/2 和 SPDY 允许对同一个主机的所有请求,使用一个 socket。
  4. 如果不支持 SPDY 的话,可以用连接池减少请求等待时间。
  5. GZIP 缩小传输大小。
  6. 缓存响应(response caching)彻底避免重复请求。
  7. 网络异常时重试。
  8. 如果服务有多个 ip ,如果第一个 ip 链接失败时 OkHttp 会尝试切换到其他 ip 。failover
  9. OkHttp 2.0 API 支持同步阻塞式调用(synchronous blocking calls)和异步回调(async calls with callbacks)。
  10. 不需要重写网络相关代码就可以试用 OkHttp 。okhttp-urlconnection 模块实现了常用的 java.net.HttpURLConnection 的API,okhttp-apache 模块实现了 Apache HttpClient 的 API 。

Calls

  1. 支持重定向(302)等。默认自动 重定向。
  2. 如果 resposne 提出验证权限,OkHttp 会向 Authenticator 询问权限。
  3. 请求分为同步和异步
  • 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.
  1. 请求可以从任何线程取消。如果取消时正在“writing the request body”或“reading the response body”,会收到一个 IOExceptioin 。

Connections

  1. 没读懂。

Recipes(菜谱)

  1. 默认是不缓存的。想要缓存响应(responses)的话,需要制定缓存目录和缓存大小。并且需要有 ETag 之类的 header 配合。 Response Caching

interceptors

  1. Interceptors
  2. Interceptors 分为 Application InterceptorsNetwork Interceptors
  3. Interceptors 可以是一系列的。(Interceptors can be chained.)按顺序执行。
  4. 一般在 Interceptors 中做这些:
  • 压缩
  • 处理 http header
  • 打印日志
  • ...
  1. 如果自动重定向的话(302等),Network Interceptors 能拦截到两次,Application Intercepors 只能拦截到一次。因为重定向是在 OkHttp Core 中执行的。

HTTPS

还没看!

posted @ 2015-11-06 11:38  shang1jk  阅读(288)  评论(0编辑  收藏  举报