OkHttp3源码详解(一) Request类,2021年Android开发实战
HttpUrl主要用来规范普通的url连接,并且解析url的组成部分
现通过下面的例子来示例httpUrl的使用
https://www.google.com/search?q=maplejaw
①使用parse解析url字符串:
- HttpUrl url = HttpUrl.parse(“https://www.google.com/search?q=maplejaw”);
②通过构造者模式来常见:
HttpUrl url = new HttpUrl.Builder()
.scheme(“https”)
.host(“www.google.com”)
.addPathSegment(“search”)
.addQueryParameter(“q”, “maplejaw”)
.build();
2.Headers
``````````Headers用于配置请求头,对于请求头配置大家一定不陌生吧,比如Content-Type,User-Agent和Cache-Control等等。````````````` 创建Headers也有两种方式。如下: (1)of()创建:传入的数组必须是偶数对,否则会抛出异常。`
- Headers.of(“name1”,“value1”,“name2”,“value2”,…);
还可以使用它的重载方法of(Map<String,String> map)方法来创建
(2)构建者模式创建:``````````````````````````
1.
Headers mHeaders=new Headers.Builder()
.set(“name1”,“value1”)//set表示name1是唯一的,会覆盖掉已经存在的
.add(“name2”,“value2”)//add不会覆盖已经存在的头,可以存在多个
.build();
我们来看一下Header的内部,源码就不粘贴了很简单,Headers内部是通过一个数组来保存header private final String[] namesAndValues;大家可能会有这样的疑问,为什么不用Map而用数组呢?因为Map的Key是唯一的,而header要求不唯一
另外,数组方便取数据吗?很方便,我们来看着三个方法
最后通过toString方法转变成String,方便写入请求头,
@Override
public String toString() {
StringBuilder result = new StringBuilder();
, size = size(); i < size; i++) {
result.append(name(i)).append(": “).append(value(i)).append(”\n");
}
return result.toString();
}
/** Returns the field at {@code position} or null if that is out of range. */
public String name(int index) {
;
|| nameIndex >= namesAndValues.length) {
return null;
}
return namesAndValues[nameIndex];
}
/** Returns the value at {@code index} or null if that is out of range. */
public String value(int index) {
* ;
|| valueIndex >= namesAndValues.length) {
return null;
}
return namesAndValues[valueIndex];
}
3.RequestBody
requestBody也就是请求实体内容,我们先来看一下如何来构建一个RequestBody
(1)Request.create()方法创建

public static final MediaType TEXT = MediaType.parse(“text/plain; charset=utf-8”);
public static final MediaType STREAM = MediaType.parse(“application/octet-stream”);
public static final MediaType JSON = MediaType.parse(“application/json; charset=utf-8”);
//构建字符串请求体
RequestBody body1 = RequestBody.create(TEXT, string);
//构建字节请求体
RequestBody body2 = RequestBody.create(STREAM, byte);
//构建文件请求体
RequestBody body3 = RequestBody.create(STREAM, file);
//post上传json
RequestBody body4 = RequestBody.create(JSON, json);//json为String类型的
//将请求体设置给请求方法内
Request request = new Request.Builder()
.url(url)
.post(xx)// xx表示body1,body2,body3,body4中的某一个
.build();
(2)构建表单请求体,提交键值对(OkHttp3没有FormEncodingBuilder这个类,替代它的是功能更加强大的FormBody:)
//构建表单RequestBody
RequestBody formBody=new FormBody.Builder()
.add(“name”,“maplejaw”)
.add(")
…
.build();
(3)构建分块表单请求体:(OkHttp3取消了MultipartBuilder,取而代之的是MultipartBody.Builder()
既可以添加表单,又可以也可以添加文件等二进制数据)
public static final MediaType STREAM = MediaType.parse(“application/octet-stream”);
//构建表单RequestBody
RequestBody multipartBody=new MultipartBody.Builder()
.setType(MultipartBody.FORM)//指明为 multipart/form-data 类型
.addFormDataPart(") //添加表单数据
.addFormDataPart(“avatar”,“111.jpg”,RequestBody.create(STREAM,file)) //添加文件,其中avatar为表单名,111.jpg为文件名。
.addPart(…)//该方法用于添加RequestBody,Headers和添加自定义Part,一般来说以上已经够用
.build();
知道了RequestBody的创建,我们来看一下源码
RequestBody也就是请求实体内容,对于一个Get请求时没有实体内容的,Post提交才有,而且浏览器与服务器通信时基本上只有表单上传才会用到POST提交,所以RequestBody其实也就是封装了浏览器表单上传时对应的实体内容,对于实体内容是什么样还不清楚的可以去看一下我的一篇博客Android的Http协议的通信详解
OkHttp3中RequestBody有三种创建方式
①方式一:
public static RequestBody create(MediaType contentType, String content) {
Charset charset = Util.UTF_8;
if (contentType != null) {
charset = contentType.charset();//MediaType的为请求头中的ContentType创建方式:public static final MediaType TEXT =
//MediaType.parse(“text/plain; charset=utf-8”)
if (charset == null) {
charset = Util.UTF_8;//如果contentType中没有指定charset,默认使用UTF-8
contentType = MediaType.parse(contentType + “; charset=utf-8”);
}
}
byte[] bytes = content.getBytes(charset);
return create(contentType, bytes);
}
②方式二:FormBody表单创建,我们来看一下
FormBody用于普通post表单上传键值对,我们先来看一下创建的方法,再看源码
RequestBody formBody=new FormBody.Builder()
.add(“name”,“maplejaw”)
.add(")
…
.build();
FormBody源码
public final class FormBody extends RequestBody {
private static final MediaType CONTENT_TYPE =
MediaType.parse(“application/x-www-form-urlencoded”);
private final List encodedNames;
private final List encodedValues;
private FormBody(List encodedNames, List encodedValues) {
this.encodedNames = Util.immutableList(encodedNames);
this.encodedValues = Util.immutableList(encodedValues);
}
/** The number of key-value pairs in this form-encoded body. */
public int size() {
return encodedNames.size();
}
public String encodedName(int index) {
return encodedNames.get(index);
}
public String name(int index) {
return percentDecode(encodedName(index), true);
}
public String encodedValue(int index) {
return encodedValues.get(index);
}
public String value(int index) {
return percentDecode(encodedValue(index), true);
}
@Override public MediaType contentType() {
return CONTENT_TYPE;
}
@Override public long contentLength() {
return writeOrCountBytes(null, true);
}
@Override public void writeTo(BufferedSink sink) throws IOException {
writeOrCountBytes(sink, false);
}
/**
* Either writes this request to {@code sink} or measures its content length. We have one method
* do double-duty to make sure the counting and content are consistent, particularly when it comes
* to awkward operations like measuring the encoded length of header strings, or the
* length-in-digits of an encoded integer.
*/
private long writeOrCountBytes(BufferedSink sink, boolean countBytes) {
long byteCount = 0L;
Buffer buffer;
if (countBytes) {
buffer = new Buffer();
} else {
buffer = sink.buffer();
}
, size = encodedNames.size(); i < size; i++) {
) buffer.writeByte(’&’);
buffer.writeUtf8(encodedNames.get(i));
buffer.writeByte(’=’);
buffer.writeUtf8(encodedValues.get(i));
}
if (countBytes) {
byteCount = buffer.size();
buffer.clear();
}
return byteCount;
}
public static final class Builder {
private final List names = new ArrayList<>();
private final List values = new ArrayList<>();
public Builder add(String name, String value) {
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, false, false, true, true));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, false, false, true, true));
return this;
}
public Builder addEncoded(String name, String value) {
names.add(HttpUrl.canonicalize(name, FORM_ENCODE_SET, true, false, true, true));
values.add(HttpUrl.canonicalize(value, FORM_ENCODE_SET, true, false, true, true));
return this;
}
public FormBody build() {
return new FormBody(names, values);
}
}
}
``````````````我们主要来看一下方法````````````````writeOrCountBytes``````````````````````````````,通过writeOrCountBytes来计算请求体大小和将请求体写入BufferedSink。
关于Buffer Sink及其所属的缓冲层机制,在Okio框架中有着重要的应用。其中缓冲层可视为一个缓存区域,在数据传输过程中起到临时存储作用。而后者则类似于OutputStream的功能,并在此基础上进行了扩展。
OutputStream的功能,Okio的完整源码我后续也会写博客
③方式三:MultipartBody分块表单创建
MultipartBody是一个灵活的参数类型,在创建 multipart 表单时非常强大;它不仅支持直接插入表单字段(Forms fields),还可以用于添加文件或其他二进制数据;我们就可以利用它来实现多种功能
public static Part createFormData(字符串name, 文件名 filename, RequestBody body) {
if (name == null) {
throw new NullPointerException(“name == null”);
}
StringBuilder disposition = new StringBuilder(“form-data; name=”);
appendQuotedString(disposition, name);
if (filename != null) {
disposition.append("; filename=");
appendQuotedString(dispositio
docs.qq.com/doc/DSkNLaERkbnFoS0ZF
《Android学习要点总结+最新移动架构教学视频+各大厂安卓面试真题+项目实战源码解析》
n, filename);
}
生成一个包含头信息并设置值的操作:
headers = new Headers();
headers->of("Content-Disposition", $disposition->toString());
然后将body传递给create函数以生成结果对象。
}
让我们分析一下该方法,在选择时需要考虑的是是否使用addPart或addFormDataPart最后都导向了这一过程。将它们封装为一个Part对象,则等价于将它们整合到实体内容中。
的Content-Disposition跟文件二进制流或者键值对的值
````````````````MultipartBody和FormBody大体上相同,主要区别在于`writeOrCountBytes方法,分块表单主要是将每个块的大小进行累加来求出请求体大小,如果其中有一个块没有指定大小,就会返回-1。所以分块表单中如果包含文件,默认是无法计算出大小的,除非你自己给文件的RequestBody指定contentLength。`````````````````
1.
private long writeOrCountBytes(BufferedSink sink, boolean countBytes) throws IOException {
long byteCount = 0L;
Buffer byteCountBuffer = null;
if (countBytes) {
//如果是计算大小的话,就new个
sink = byteCountBuffer = new Buffer();
}
//循环块
, partCount = parts.size(); p < partCount; p++) {
Part part = parts.get§;
//获取每个块的头
Headers headers = part.headers;
//获取每个块的请求体
RequestBody body = part.body;
//写 --xxxxxxxxxx 边界
sink.write(DASHDASH);
sink.write(boundary);
sink.write(CRLF);
//写块的头
if (headers != null) {
, headerCount = headers.size(); h < headerCount; h++) {
sink.writeUtf8(headers.name(h))
.write(COLONSPACE)
.writeUtf8(headers.value(h))
.write(CRLF);
}
}
//写块的Content_Type
MediaType contentType = body.contentType();
if (contentType != null) {
sink.writeUtf8("Content-Type: ")
.writeUtf8(contentType.toString())
.write(CRLF);
}
