【发布时间】:2016-04-28 01:51:00
【问题描述】:
如何使用OkHttp v3 管理动态文件数的上传,我已经使用旧版本的 OkHttp 实现了 compile 'com.squareup.okhttp:okhttp:2.6.0'
Form 类有一些变化,现在对 Multipart 主体进行了建模。他们用更强大的 FormBody 和 FormBody.Builder 组合替换了不透明的 FormEncodingBuilder。同样,他们将 MultipartBuilder 升级为 MultipartBody、MultipartBody.Part 和 MultipartBody.Builder。
以下代码为旧版本
final MediaType MEDIA_TYPE = MediaType.parse(AppConstant.arrImages.get(i).getMediaType());
//If you can have multiple file types, set it in ArrayList
MultipartBuilder buildernew = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("title", title); //Here you can add the fix number of data.
for (int i = 0; i < AppConstants.arrImages.size(); i++) { //loop to add dynamic number of files.
File f = new File(FILE_PATH,TEMP_FILE_NAME + i + ".png");
if (f.exists()) {
buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f));
}
}
RequestBody requestBody = buildernew.build();
//Build the object of MultipartBuilder and get object of RequestBody.
但现在对于OkHttp <version>3.0.1</version> 文件上传的代码实现类似于下面的代码(source)
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
我尝试了与MultipartBody 相同的逻辑,但没有找到任何富有成效的解决方案。
或者我是否需要针对不同的情况实施相同的if else。(这是不可行的)
【问题讨论】:
标签: android file-upload okhttp okhttp3