OkHttp4 RequestBodycreate()弃用

OKhttp3已升级到Okhttp4 ,编写语言由java过渡到kotlin

okhttp3经常用到的post提交数据的,RequestBody.create() 已过时,并且换成了kotlin的新特性写法!

okhttp3 post请求的代码(4.0版本已过时) :

1
2
3
4
kotlin复制代码
val request:Request=Request.Builder()
.post(RequestBody.create(MediaType.parse("application/json;charset=utf8"),
"body参数")).build()

okhttp4 post最新请求的代码:

Kotlin版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
kotlin复制代码import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.RequestBody.Companion.asRequestBody

//String转RequestBody String、ByteArray、ByteString都可以用toRequestBody()
val stringBody ="body参数".toRequestBody("application/json;charset=utf-8".toMediaType())
val request = Request
.Builder()
.post(stringBody)
.build()

//File转RequestBody
val file=File("")
val fileBody=file.asRequestBody("text/x-markdown; charset=utf-8".toMediaType())
val request = MultipartBody.Builder()
.addFormDataPart("file", file.name,fileBody)
.build()

Java版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
java复制代码
import okhttp3.MediaType.Companion.*;
import okhttp3.RequestBody.Companion.*;

//String转RequestBody String、ByteArray、ByteString都可以用toRequestBody()
MediaType mediaType=MediaType.Companion.parse("application/json;charset=utf-8");
RequestBody stringBody=RequestBody.Companion.create("body参数",mediaType);
Request request=new Request
.Builder()
.post(stringBody)
.build();

//File转RequestBody
MediaType mediaType=MediaType.Companion.parse("text/x-markdown; charset=utf-8");
File file=new File("");
RequestBody fileBody=RequestBody.Companion.create(file,mediaType);
Request request=new MultipartBody.Builder()
.addFormDataPart("file", file.getName(),fileBody)
.build();

官方迁移指南

参考链接

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%