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()
编译器提示如下:

okhttp4.0过时

又是一个小技巧

最后修改:2022 年 12 月 04 日 06 : 16 PM
如果觉得我的文章对你有用,请随意赞赏