数据类型可参考https://www.runoob.com/http/http-content-type.html
1、准备上传文件(练习直接指定)
File file1 = new File("D:\\1.txt");
2、文件上传Builder
上传使用 MultipartBody
上传文件addFormDataPart(name: String, filename: String?, body: RequestBody)
第一个参数:文件标识(我的理解是上传后的名称)
第二个参数:上传文件的本地名,或者说是实际名称
第三个参数:文件/数据的类型(可以参考上面的地址,找对应类型)
3、OkHttp的基本请求
这个和之前都差不多,多了一个MultipartBody 传进请求中,通过post(multipartBody)
文件上传代码示例
public void UpLoadFile() {
File file1 = new File("D:\\1.txt");
MultipartBody multipartBody = new MultipartBody.Builder()
.addFormDataPart("file", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
.addFormDataPart("a","test")
.build();
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://www.httpbin.org/post")
.post(multipartBody)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response =call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
1、准备请求主体内容,通过RequestBody
RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", MediaType.parse("application/json"));
一看就知道,RequestBody.create的参数,第一参数:数据内容(json串),第二个参数:数据类型
2、OkHttp的基本请求
public void SendJson() {
RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", MediaType.parse("application/json"));
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://www.httpbin.org/post")
.post(requestBody)
.build();
Call call = okHttpClient.newCall(request);
Response response = null;
try {
response = call.execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
1、文件上传
MultipartBody multipartBody = new MultipartBody.Builder()
.addFormDataPart("file", file1.getName(), RequestBody.create(file1, MediaType.parse("text/plain")))
.addFormDataPart("a","test")
.build();
2、数据上传
RequestBody requestBody = RequestBody.create("{\"a\":1,\"b\":2}", MediaType.parse("application/json"));
3、okHttpClient的基础应用