协议规定POST提交的数据必须放在请求体中,但协议并没有规定数据必须使用什么编码方式。而常用的数据编码方式有:
https://www.runoob.com/http/http-content-type.html
列举几种最常见的数据格式:
- Content-Type: application/x-www-form-urlencoded 数据被编码为名称/值对,默认类型;
- Content-Type: multipart/form-data 数据被编码为一条消息,一般用于文件上传;
- Content-Type:application/octet-stream 提交二进制数据,如果用于文件上传,只能上传一个文件
- Content-Type:application/json 提交json数据
1、多个文件上传
File filel = new File( pathname: "C:\\Users\\Administrator\\Desktop\\1.txt");
File file2 = new File( pathname: "C:\\Users\\Administrator\\Desktop\\2.txt");
MultipartBody multipartBody = new MultipartBody.Builder()
.addFormDataPart(name:"file1",filel.getName(), RequestBody.create(filel,Mediatype.parse(("text/plain"))
.addFormDataPart(name: "file2",file2.getName(), RequestBody.create(file2,MediaType.parse(("text/plain"))
.addFormDataPart(name:"a",value: "1")
.build();
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(multipartBody).build
2、Json上传
RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", Mediatype.porse(""application/json"))
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();