压缩包:
一、POST请求
协议规定POST提交的数据必须放在请求体中,但协议并没有规定数据必须使用什么编码方式。而常用的数据编码方式有:
[https://www.runoob.com/http/http-content-type.html](https://www.runoob.com/http/http-content-type.html)<br /> Content-Type:application/x-www-form-urlencoded<br /> 数据被编码为名称/值对,默认类型;<br /> Content-Type:multiparty/form-data<br /> 数据被编码为一条消息,一般用于文件上传;<br /> Content-Type:application/octet-stream<br /> 提交二进制数据,如果用于文件上传,只能上传一个文件;<br /> Content-Type:application/json<br /> 提交json数据
二、post的请求放在test的java文件下
三、整体代码
1.UploadFileUnitTest类文件代码:
package com.example.networkdemo;import org.junit.Test;import java.io.File;import java.io.IOException;import okhttp3.Call;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;public class UploadFileUnitTest { @Test public void uploadFileTest() throws IOException { OkHttpClient okHttpClient = new OkHttpClient(); File file1 = new File("C:\\Users\\ASUS\\Desktop\\1.txt"); File file2 = new File("C:\\Users\\ASUS\\Desktop\\2.txt"); MultipartBody multipartBody = new MultipartBody.Builder() .addFormDataPart("file1", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain"))) .addFormDataPart("file2", file2.getName(), RequestBody.create(file2, MediaType.parse("text/plain"))) .addFormDataPart("a","1") .build(); Request request = new Request.Builder().url("https://www.httpbin.org/post") .post(multipartBody).build(); Call call = okHttpClient.newCall(request); Response response = call.execute(); System.out.println(response.body().string()); }}