设为首页 加入收藏

TOP

Okhttp3源码解析(2)-Request分析(二)
2019-09-03 03:36:58 】 浏览:74
Tags:Okhttp3 源码 解析 -Request分析
cnblogs.com/blog/1312938/201908/1312938-20190823180242513-433063641.png) 如果是POST请求,就需要我们去设定了 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190823180242695-600270897.png) ### RequestBody解析 首先我们看一下RequestBody如何初始化??拿提交表单举例: ``` RequestBody requestBody = new FormBody.Builder() .add("username", "qinzishuai") .add("password", "000000") .build(); ``` 不出所料,也是Builder模式,而且`RequestBody` 是抽象类, `FormBody`是`RequestBody`的其中一种实现类 ,另一个实现类是`MultipartBody` RequestBody源码如下: ``` public abstract class RequestBody { /** Returns the Content-Type header for this body. */ public abstract @Nullable MediaType contentType(); /** * Returns the number of bytes that will be written to {@code sink} in a call to {@link #writeTo}, * or -1 if that count is unknown. */ public long contentLength() throws IOException { return -1; } /** Writes the content of this request to {@code sink}. */ public abstract void writeTo(BufferedSink sink) throws IOException; /** * Returns a new request body that transmits {@code content}. If {@code contentType} is non-null * and lacks a charset, this will use UTF-8. */ public static RequestBody create(@Nullable MediaType contentType, String content) { Charset charset = Util.UTF_8; if (contentType != null) { charset = contentType.charset(); if (charset == null) { charset = Util.UTF_8; contentType = MediaType.parse(contentType + "; charset=utf-8"); } } byte[] bytes = content.getBytes(charset); return create(contentType, bytes); } /** Returns a new request body that transmits {@code content}. */ public static RequestBody create( final @Nullable MediaType contentType, final ByteString content) { return new RequestBody() { @Override public @Nullable MediaType contentType() { return contentType; } @Override public long contentLength() throws IOException { return content.size(); } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(content); } }; } /** Returns a new request body that transmits {@code content}. */ public static RequestBody create(final @Nullable MediaType contentType, final byte[] content) { return create(contentType, content, 0, content.length); } //省略部分代码... } ``` 核心方法有三个: - contentType()//数据类型 - contentLength()//数据长度 - writeTo(BufferedSink sink) //写操作 今天就讲到这里,希望对大家有所帮助... 大家可以关注我的微信公众号:「秦子帅」一个有质量、有态度的公众号! ![公众号](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190823180242882-2108811045.jpg)
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android Studio修改Apk打包生成名.. 下一篇Okhttp3源码解析(1)-OkHttpClient..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目