前段时间,OKhttp3已升级到Okhttp4 ,编写语言由java过渡到kotlin,而以前okhttp3经常用到的post提交数据的:
已过时,并且换成了kotlin的新特性写法!RequestBody.create()
okhttp3 post请求的代码(4.0版本已过时) :
val request:Request=Request
.Builder()
.post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"body参数"))
.build()
- 1
- 2
- 3
- 4
okhttp4 post最新请求的代码:
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=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()
- 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();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
这就是okhttp4.0最新post带参数请求的代码,虽然官方专门出了升级指南但是可能由于编译器不是最新的版本,在使用toRequestBody()
的时候,编译器一直不提示引入包,所以折腾了很长时间。
如果编译器不提示引入包,记得自己手动加上就可以了