OKhttp中的okio、拦截器、响应
前言:本篇博客将由浅入深地对OKhttp进行解析,包括基本使用、okio、拦截器和响应等内容,和读者一起全面系统地了解OKhttp的知识,深入了解Android客户端网络请求方法及过程,学习OKhttp采用的设计模式和架构。
一、OKhttp概述:
HTTP是现代应用常用的一种交换数据和媒体的网络方式,高效地使用HTTP能让资源加载更快,节省带宽。OkHttp是一个高效的HTTP客户端,它有以下默认特性:
- 支持HTTP/2,允许所有同一个主机地址的请求共享同一个socket连接
- 连接池减少请求延时
- 透明的GZIP压缩减少响应数据的大小
- 缓存响应内容,避免一些完全重复的请求
以下内容将从“OKhttp地基本使用”、“源码分析”、“OKhttp架构分析”
1-OKhttp的使用:
添加依赖:
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
最新版本请在https://github.com/square/okhttp官网查询,由于OKhttp要用到网络请求,所以不要忘记再AndroidManifest中配置网络请求。
GET异步请求:
/**
* new OkHttpClient;
* 构造Request对象;
* 通过前两步中的对象构建Call对象;
* 通过Call#enqueue(Callback)方法来提交异步请求;
*/
String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, "onResponse: " + response.body().string());
}
});
GET同步请求:
/**
* 前面几个步骤和异步方式一样,只是最后一部是通过 Call#execute() 来提交请求,
* 注意这种方式会阻塞调用线程,所以在Android中应放在子线程中执行,否则有可能引起ANR异常,
*/
String url = "http://wwww.baidu.com";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.build();
final Call call = okHttpClient.newCall(request);
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = call.execute();
Log.d(TAG, "run: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
POST方式提交String请求:
这种方式与前面的区别就是在构造Request对象时,需要多构造一个RequestBody对象,用它来携带我们要提交的数据。在构造 RequestBody
需要指定MediaType
,用于描述请求/响应 body
的内容类型,关于 MediaType
可以查看https://tools.ietf.org/html/rfc2045
import okhttp3.*;
import java.io.IOException;
/**
* @author houbo
*/
public class OKhttpDemo {
public static void main(String[] args) {
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
String requestString = "I am a good boy";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(mediaType,requestString))
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.protocol()+" "+response.code()+" "+response.message());
Headers headers = response.headers();
for (int i=0;i<headers.size();i++){
System.out.println(headers.name(i)+":"+headers.value(i));
}
System.out.println(response.body().string());
}
});
}
}
响应结果:
http/1.1 200 OK
Date:Sun, 06 Sep 2020 09:01:15 GMT
Content-Type:text/html;charset=utf-8
Transfer-Encoding:chunked
Server:GitHub.com
Status:200 OK
X-CommonMarker-Version:0.21.0
X-RateLimit-Limit:60
X-RateLimit-Remaining:59
X-RateLimit-Reset:1599386475
X-RateLimit-Used:1
Access-Control-Expose-Headers:ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset
Access-Control-Allow-Origin:*
Strict-Transport-Security:max-age=31536000; includeSubdomains; preload
X-Frame-Options:deny
X-Content-Type-Options:nosniff
X-XSS-Protection:1; mode=block
Referrer-Policy:origin-when-cross-origin, strict-origin-when-cross-origin
Content-Security-Policy:default-src 'none'
Vary:Accept-Encoding, Accept, X-Requested-With
Vary:Accept-Encoding
X-GitHub-Request-Id:0CB8:5D4D:44BFC2:5CCD3F:5F54A559
<p>I am a good boy</p>
POST方式提交流请求:
import okhttp3.*;
import okio.BufferedSink;
import java.io.IOException;
/**
* @author houbo
*/
public class HttpDemo2 {
public static void main(String[] args) {
RequestBody requestBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("text/x-markdown; charset=utf-8");
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("I am good boy");
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.protocol()+" "+response.code()+" "+response.message());
Headers headers = response.headers();
for (int i=0;i<headers.size();i++){
System.out.println(headers.name(i)+":"+headers.value(i));
}
System.out.println(response.body().string());
}
});
}
}
POST提交文件请求:
import okhttp3.*;
import java.io.File;
import java.io.IOException;
/**
* @author houbo
*/
public class HttpDemo3 {
public static void main(String[] args) {
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
OkHttpClient client = new OkHttpClient();
File file = new File("test.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(mediaType,file))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.protocol()+" "+response.code()+" "+response.message());
Headers headers = response.headers();
for (int i=0;i<headers.size();i++){
System.out.println(headers.name(i)+":"+headers.value(i));
}
System.out.println(response.body().string());
}
});
}
}
POST提交表单请求:
import okhttp3.*;
import java.io.IOException;
/**
* @author houbo
*/
public class HttpDemo4 {
public static void main(String[] args) {
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("search","davilk")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.protocol()+" "+response.code()+" "+response.message());
Headers headers = response.headers();
for (int i=0;i<headers.size();i++){
System.out.println(headers.name(i)+":"+headers.value(i));
}
System.out.println(response.body().string());
}
});
}
}
POST方式提交分块请求:
import okhttp3.*;
import java.io.File;
import java.io.IOException;
public class HttpDemo5 {
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private void postMultipartBody() {
OkHttpClient client = new OkHttpClient();
// 构造多块请求体
MultipartBody body = new MultipartBody.Builder("AaB03x")
.setType(MultipartBody.FORM)//表单形式
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println(response.body().string());
}
});
}
}
二、拦截器 interceptor
OkHttp的拦截器链可谓是其整个框架的精髓,用户可传入的 interceptor
分为两类:
- 一类是全局的
interceptor
,该类interceptor
在整个拦截器链中最早被调用,通过OkHttpClient.Builder#addInterceptor(Interceptor)
传入; - 另外一类是非网页请求的
interceptor
,这类拦截器只会在非网页请求中被调用,并且是在组装完请求之后,真正发起网络请求前被调用,所有的interceptor
被保存在List<Interceptor> interceptors
集合中,按照添加顺序来逐个调用,具体可参考RealCall#getResponseWithInterceptorChain()
方法。通过OkHttpClient.Builder#addNetworkInterceptor(Interceptor)
传入;
例如有这样一个需求,我要监控App通过 OkHttp
发出的所有原始请求,以及整个请求所耗费的时间,针对这样的需求就可以使用第一类全局的 interceptor
在拦截器链头去做。
OkHttpClient okHttpClient = 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();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, "onResponse: " + response.body().string());
body.close();
}
}
});
//================================================================================
public class LoggingInterceptor implements Interceptor {
private static final String TAG = "LoggingInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long endTime = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
return response;
}
}
完整的拦截器链:
三、重点注意点
- 推荐让
OkHttpClient
保持单例,用同一个OkHttpClient
实例来执行你的所有请求,因为每一个OkHttpClient
实例都拥有自己的连接池和线程池,重用这些资源可以减少延时和节省资源,如果为每个请求创建一个OkHttpClient
实例,显然就是一种资源的浪费。当然,也可以使用如下的方式来创建一个新的OkHttpClient
实例,它们共享连接池、线程池和配置信息。
OkHttpClient eagerClient = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
Response response = eagerClient.newCall(request).execute();
- 每一个Call(其实现是RealCall)只能执行一次,否则会报异常,具体参见
RealCall#execute()