OkHttp4 写法
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()
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();
4.0之前写法:
val request:Request=Request
.Builder()
.post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"),"body参数"))
.build()
编译器提示如下:
又是一个小技巧
版权属于:Monster_4y
本文链接:https://blog.zmonster.top/93.html
转载时须注明出处及本声明