OKHttp上传文件带参数简单使用三部曲:
构建以下三个对象:
MultipartBody.Builder()
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
RequestBody
RequestBody requestBody=builder.build();
Request
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
/**
* 上传图片附带参数
* @param url 路径
* @param photoPaths 图片路径
* @param dir 输入api参数
* @param callback 回调接口
*/
public static void uploadImage(String url, String photoPaths, String dir, Callback callback){
File file = new File(photoPaths);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("dir", dir)
.addFormDataPart(file.getName(), file.getName(),RequestBody.create(MEDIA_TYPE_MARKDOWN, file)).build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(callback);
}
MultipartBody支持同时上传多个文件,在MultipartBody.Builder对象循环添加文件参数即可。
GitHub原地址:
OkHttp WIKI