Android okHttp-Post的提交数据方式
Posted 森然献凉i
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android okHttp-Post的提交数据方式相关的知识,希望对你有一定的参考价值。
说明:学习记录
HTTP content-type 对照表:https://www.runoob.com/http/http-content-type.html
post上传多个文件
//post上传多个文件
@Test
public void uploadFileUnitTest() throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
File file1 = new File("C:\\\\Users\\\\uzi\\\\Desktop\\\\1.txt");
File file2 = new File("C:\\\\Users\\\\uzi\\\\Desktop\\\\2.txt");
//通过创建RequestBody指定MediaType
RequestBody re1 = RequestBody.create(file1, MediaType.parse("text/plain"));
RequestBody re2 = RequestBody.create(file2, MediaType.parse("text/plain"));
//使用multipartBody方式提交
MultipartBody multipartBody = new MultipartBody.Builder()
//添加文件
.addFormDataPart("file1", file1.getName(), re1)
.addFormDataPart("file2", file2.getName(), re2)
.build();
//Request封装请求地址,参数
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(multipartBody).build();
//准备好请求的call对象
Call call=okHttpClient.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
post上传json数据
//post上传json数据
@Test
public void json() throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
//通过创建RequestBody指定MediaType
RequestBody requestBody = RequestBody.create("{\\"a\\":1,\\"b\\":2}", MediaType.parse("application/json"));
//Request封装请求地址,参数
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();
//准备好请求的call对象
Call call=okHttpClient.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}
结束
以上是关于Android okHttp-Post的提交数据方式的主要内容,如果未能解决你的问题,请参考以下文章