先贴出okhttp的官网:http://square.github.io/okhttp/
AS中的依赖 :compile 'com.squareup.okhttp3:okhttp:3.9.0'
一、官网概述
OkHttp默认是一个有效的HTTP客户端:
1、HTTP / 2支持允许所有请求相同的主机共享一个套接字。
2、连接池可以减少请求延迟(如果HTTP / 2不可使用),http的握手次数。
3、透明的GZIP收缩下载大小。
4、响应缓存避免了网络完全重复请求。
个人理解:
首先OkHttp是一款优秀的网络请求框架,这点有别于Retrofit(进一步的封装而已)。同时简化了客户端对网络请求操作(使用构建者模式,同步异步,各种异常的处理,请求报文和响应报文的封装)。底层使用的Socket和隧道的方式执行网络请求,这个我也没怎么看。它内部使用了连接池来复用可用的连接,以及用了DiskLruCache缓存来减少对网络的请求次数,在一定的时间段中,直接返回缓存内容。
二、简单使用
1、同步请求
对于使用者来说非常的简单,只需要四步即可
第一步:构建一个OkHttp客户端对象,还有很多参数可以设置
OkHttpClient client = new OkHttpClient.Builder() // 构建者模式构建
.addInterceptor(new Interceptor() { // 添加一个拦截器,可以在拦截器中做一些公共的处理
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Request.Builder requestBuilder = request.newBuilder();
return chain.proceed(requestBuilder.build());
}
})
.cache(new Cache(new File("cache"), 5 * 1024 * 1024)) // 缓存设置
.readTimeout(5, TimeUnit.SECONDS).build(); // 读取时间设置并build生成对象
第二步:构建一个请求体,Request,同样采用Builder模式
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
第三步:将请求参数传入给真正的执行者,前面都是一些条件的配置,这里是将参数传给RealCall(实现了Call接口)这个真正的执行者,Call里面有同步和异步的执行方法
Call call = client.newCall(request);
第四步:开始执行,并得到返回体Response
Response response = call.execute();
2、异步请求
异步请求和同步请求的前三步一致,只是调用Call的方法不一样
异步的第四步:需要传入一个接口对象给Call,这样接到返回回来后,才能回调给调用者
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) { // 失败的回调
}
@Override
public void onResponse(Call call, Response response) throws IOException {// 成功的回调
}
对于okhttp的简单使用就介绍到这,后面可能会继续补充。
三、OkHttpClient类的介绍
截取了OkHttpClient的部分介绍
* Factory for {@linkplain Call calls}, which can be used to send HTTP requests and read their
* responses.
*
* <h3>OkHttpClients should be shared</h3>
*
* <p>OkHttp performs best when you create a single {@code OkHttpClient} instance and reuse it for
* all of your HTTP calls. This is because each client holds its own connection pool and thread
* pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a
* client for each request wastes resources on idle pools.
*
* <p>Use {@code new OkHttpClient()} to create a shared instance with the default settings:
* <pre> {@code
*
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient();
* }</pre>
*
* <p>Or use {@code new OkHttpClient.Builder()} to create a shared instance with custom settings:
* <pre> {@code
*
* // The singleton HTTP client.
* public final OkHttpClient client = new OkHttpClient.Builder()
* .addInterceptor(new HttpLoggingInterceptor())
* .cache(new Cache(cacheDir, cacheSize))
* .build();
* }</pre>
*
* <h3>Customize your client with newBuilder()</h3>
*
* <p>You can customize a shared OkHttpClient instance with {@link #newBuilder()}. This builds a
* client that shares the same connection pool, thread pools, and configuration. Use the builder
* methods to configure the derived client for a specific purpose.
*
* <p>This example shows a call with a short 500 millisecond timeout: <pre> {@code
*
* OkHttpClient eagerClient = client.newBuilder()
* .readTimeout(500, TimeUnit.MILLISECONDS)
* .build();
* Response response = eagerClient.newCall(request).execute();
* }</pre>
他的大致意思是:
OkHttpClient 最好使用单例的方式,一个客户端最好只有一个OkHttpClient 实例。原因就是OkHttpClient 中保存的有连接池和线程池,也就是RealCall代表了一次真正的http请求,OkHttpClient 中会用算法保存很多RealCall。创建OkHttpClient 时候最好通过Builder模式,如果用想实现多个OkHttpClient 实例,可以通过newBuilder()来创建,这样的话就可以共用一个 connection pool, thread pools, and configuration。
OkHttpClient成员变量
在build构建的时候会为这些成员变量赋值,可能是默认的也可能是自己传入的;
如Dispatcher分发处理器和Intercepter拦截器链等,这些都是可以复用的,所以最好只有一个OkHttpClient实例对象
OkHttpClient成员变量
在OkHttpClient中继承了下面这个接口
interface Factory {
Call newCall(Request request);
}
这个接口就是创建RealCall的实例的,生成RealCall需要该OkHttpClient客户端(得到OkHttpClient中的成员变量和方法),请求参数,Boolean参数
/**
* Prepares the {@code request} to be executed at some point in the future.
*/
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
上面的bool参数的用处,在于构建拦截器链时会用,false的时候会加载OkHttpClient中的networkInterceptors拦截器。这个是用户自定义的,做一些特殊处理用
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
OkHttpClient就是创建一些公共的变量,为以后的处理做准备。二者就是创建Call的实例对象(参数包括OkHttpClient对象自己和请求参数)。
四、Request请求参数的封装类
先看成员变量:
/**
* An HTTP request. Instances of this class are immutable if their {@link #body} is null or itself
* immutable.
*/
public final class Request {
final HttpUrl url;
final String method;
final Headers headers;
final @Nullable RequestBody body;
final Object tag;
1、HttpUrl url
HttpUrl是为何物,先看HttpUrl中的简介:
HttpUrl httpUrl= new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
httpUrl.toString()打印出来:https://www.google.com/search?q=polar%20bears
看到这里就很熟悉了,这个就是我们请求路径。
还可以解析出来:
HttpUrl url = HttpUrl.parse("https://twitter.com/search?q=cute%20%23puppies&f=images");
for (int i = 0, size = url.querySize(); i < size; i++) {
System.out.println(url.queryParameterName(i) + ": " + url.queryParameterValue(i));
}
或者相对:
HttpUrl base = HttpUrl.parse("https://www.youtube.com/user/WatchTheDaily/videos");
HttpUrl link = base.resolve("../../watch?v=cbP2N1BQdYc");
2、String method
method 代表请求方式,有GET、POST,这两个常见,此外还包括DELETE、PUT、PATCH等
3、Headers headers
Headers中包含了一次HTTP的请求头信息。
用一张图来说明,下面是一个POST请求的请求报文信息
headers 中保存的就是下图中的报文头部分,其中的部分都是以KEY - VALUE保存的。正常来说我们会用HashMap来保存这些数据,但是OkHttp却不是,原因是这些键值对数量有限,不多;
final List<String> namesAndValues = new ArrayList<>(20);
// 保存和删除
Builder addLenient(String name, String value) {
namesAndValues.add(name);
namesAndValues.add(value.trim());
return this;
}
public Builder removeAll(String name) {
for (int i = 0; i < namesAndValues.size(); i += 2) {
if (name.equalsIgnoreCase(namesAndValues.get(i))) {
namesAndValues.remove(i); // name
namesAndValues.remove(i); // value
i -= 2;
}
}
return this;
}
简单介绍几种头的含义:
3.1、Accept 客户端可以接受的媒体类型
如text/html等,通配符 * 代表任意类型
3.2、Accept-Encoding
作用: 浏览器申明自己接收的编码方法,通常指定压缩方法,是否支持压缩,支持什么压缩方法(gzip,deflate),(注意:这不是只字符编码);
例如: Accept-Encoding: gzip;OkHttp对gzip有处理
3.3、Cookie
将cookie的值发送给HTTP 服务器,用作一些处理
3.4、Content-Length
发送给HTTP服务器数据的长度,服务器通过这个来截取请求数据
3.5、Connection
例如: Connection: keep-alive 当一个网页打开完成后,客户端和服务器之间用于传输HTTP数据的TCP连接不会关闭,如果客户端再次访问这个服务器上的网页,会继续使用这一条已经建立的连接
例如: Connection: close 代表一个Request完成后,客户端和服务器之间用于传输HTTP数据的TCP连接会关闭, 当客户端再次发送Request,需要重新建立TCP连接。
3.6、Host
作用: 请求报头域主要用于指定被请求资源的Internet主机和端口号,它通常从HTTP URL中提取出来的
URL是统一资源定位器 scheme://host.domain:port/path/filename
4、RequestBody 报文体
如上图中形式。注意GET请求是没有报文体的,他的信息和url在一起。post是存在的。
RequestBody是abstract的,他的子类是有FormBody (表单提交的)和 MultipartBody(文件上传),分别对应了两种不同的MIME类型
FormBody :"application/x-www-form-urlencoded"
MultipartBody:"multipart/"+xxx.
MIME类型的作用就是描述HTTP请求或响应主体的内容类型
// 构建RequestBody ,RequestBody 中存在MediaType 和 内容两部分
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "content");
好了,到此Request里面的内容分析的差不多了,这里需要对http协议了解一点。
五 Call 执行类
Call 接口内容不多,直接copy过来
/**
* A call is a request that has been prepared for execution. A call can be canceled. As this object
* represents a single request/response pair (stream), it cannot be executed twice.
*/
public interface Call extends Cloneable {
/** Returns the original request that initiated this call. */
// 就是构建RealCall传过来的request
Request request();
/**
* Invokes the request immediately, and blocks until the response can be processed or is in
* error.
*
* <p>To avoid leaking resources callers should close the {@link Response} which in turn will
* close the underlying {@link ResponseBody}.
*
* <pre>@{code
*
* // ensure the response (and underlying response body) is closed
* try (Response response = client.newCall(request).execute()) {
* ...
* }
*
* }</pre>
*
* <p>The caller may read the response body with the response's {@link Response#body} method. To
* avoid leaking resources callers must {@linkplain ResponseBody close the response body} or the
* Response.
*
* <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
* not necessarily indicate application-layer success: {@code response} may still indicate an
* unhappy HTTP response code like 404 or 500.
*
* @throws IOException if the request could not be executed due to cancellation, a connectivity
* problem or timeout. Because networks can fail during an exchange, it is possible that the
* remote server accepted the request before the failure.
* @throws IllegalStateException when the call has already been executed.
*/
// 告诉我们,他是阻塞执行的,为了防止资源泄漏应该关闭Response;内容通过读取Response#body,用后需要关闭;
Response execute() throws IOException;
/**
* Schedules the request to be executed at some point in the future.
*
* <p>The {@link OkHttpClient#dispatcher dispatcher} defines when the request will run: usually
* immediately unless there are several other requests currently being executed.
*
* <p>This client will later call back {@code responseCallback} with either an HTTP response or a
* failure exception.
*
* @throws IllegalStateException when the call has already been executed.
*/
// 异步执行的,关闭Resonse,传递一个接口实现处理完成后回调回来
void enqueue(Callback responseCallback);
/** Cancels the request, if possible. Requests that are already complete cannot be canceled. */
void cancel();
/**
* Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain
* #enqueue(Callback) enqueued}. It is an error to execute a call more than once.
*/
// 判断是否该http是否执行过了,告诉我们只能执行一次
boolean isExecuted();
// 是否取消了,通过retryAndFollowUpInterceptor来判断
boolean isCanceled();
/**
* Create a new, identical call to this one which can be enqueued or executed even if this call
* has already been.
*/
// 通过克隆创建一个内容一样的新的RealCall对象实例
Call clone();
interface Factory {
Call newCall(Request request);
}
}
网友评论