使用okHttp3

时间:2016-01-21 17:17:57

标签: android file-upload okhttp okhttp3

如何使用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。(这是不可行的)

1 个答案:

答案 0 :(得分:15)

构建器仍然存在,可用于此目的。像以前一样将它存储在本地,然后在循环中修改:

MultipartBody.Builder buildernew = new MultipartBody.Builder()
      .setType(MultipartBody.FORM)
      .addFormDataPart("title", title);   //Here you can add the fix number of data.

for (int i = 0; i < AppConstants.arrImages.size(); i++) {
    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));
    }
}

MultipartBody requestBody = buildernew.build();