一、常用的数据编码格式
协议规定POST提交的数据必须放在请求体中,但是协议没有规定必须使用什么编码方式。而常用的数据编码方式有:
- Content - Type:application/x-www-form-urlencode:数据被编码为名称/值对,默认类型;
- Content - Type:multipart/form-data:数据被编码为一条消息,一般用于文件上传;
- Content - Typy:application/octet-stream:提交二进制数据,如果用于文件上传,只能上传一个文件;
- Content - Type:application/json:提交json数据
二、代码呈现
代码主要功能是传送两个文件
public class UploadFileUnitTeat {@Testpublic void UploadFileUnitTeat() throws IOException {//步骤一、新建一个客户端OkHttpClient okHttpClient = new OkHttpClient();//步骤二、传送文件使用multipartBody携带文件.....添加name这个name需要跟服务器商量确定一个值,第二个值传递文件的名字//步骤三、new出file对象//步骤四、把文件加给请求体File file1 = new File("C:\\Users\\Anglin\\Desktop\\1.doc");File file2 = new File("C:\\Users\\Anglin\\Desktop\\2.doc");MultipartBody multipartBody = new MultipartBody.Builder().addFormDataPart("file1", file1.getName(), RequestBody.create(file1, MediaType.parse("Text/plain"))).addFormDataPart("file2", file2.getName(), RequestBody.create(file1, MediaType.parse("Text/plain"))).build();//post请求体携带我们需要上传的文件Request request = new Request.Builder().url("https://httpbin.org/post").post(multipartBody).build();Call call = okHttpClient.newCall(request);Response response = call.execute();System.out.println(response.body().string());}
}