如何使用OkHttp v3管理上传不定数量的文件,我已经在较早版本的OkHttp中实现了这一功能,其版本为compile 'com.squareup.okhttp:okhttp:2.6.0'
Form和Multipart bodies类有所更改,他们已用更强大的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>
的文件上传,代码实现类似于下面的代码(来源):
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
。(这是不可行的)