我正在尝试使用 Retrofit2 制作一个相当复杂的 POST。
@Multipart
@FormUrlEncoded
@POST("post")
Call<JSONObject> createPost(
@Field("name") String name,
@Part("media_1") MultipartBody.Part mediaOne,
@Part("media_2") MultipartBody.Part mediaTwo,
@Part("media_3") MultipartBody.Part mediaThree,
@Part("media_4") MultipartBody.Part mediaFour,
@Part("media_5") MultipartBody.Part mediaFive,
@Header("secret_key") int secretKey
);
它包含各个方面,例如一个名为“name”的参数,我通常会认为使用 @Field 和 @FormUrlEncoded 来发布该参数。我知道我不能同时拥有 @Multipart 和 @FormUrlEncoded,所以我想我想从上面的代码示例中删除 @FormUrlEncoded 并将 @Field 替换为 @Part。这是正确的吗?
然后,我收到异常“使用 MultipartBody.Part 的 @Part 参数不得在注释中包含零件名称”。但这并不是说我可以删除 @Part("media_1") 等,因为这些部分名称可确保媒体文件上传到正确的位置。这里的解决方案是什么?
这是我做过的最复杂的 Retrofit2 调用。感谢您花时间查看我的问题。
这里是我使用 Retrofit2 调用的地方,以防万一将其作为上下文会有所帮助:
file0 = FileUtils.getFile(filePath);
requestFile0 = RequestBody.create(MediaType.parse("multipart/form-data"), file0);
body0 = MultipartBody.Part.createFormData("image0", file0.getName(), requestFile0);
file1 = FileUtils.getFile(constructedLog.getLogImageLocations().get(1));
requestFile1 = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
body1 = MultipartBody.Part.createFormData("logImage1", file1.getName(), requestFile1);
//etc for file2, file3, file4
Call<JSONObject> call = apiService.getApi().createPost(
getName(),
body0,
body1,
body2,
body3,
body4,
secretKey
);
最佳答案
API调用代码:
@Multipart
@POST("post")
Call<JSONObject> createPost(
@Part("name") RequestBody name,
@Part MultipartBody.Part mediaOne,
@Part MultipartBody.Part mediaTwo,
@Part MultipartBody.Part mediaThree,
@Part MultipartBody.Part mediaFour,
@Part MultipartBody.Part mediaFive,
@Header("secret_key") int secretKey
);
File file = new File(yourpathhere);
body0 = MultipartBody.Part.createFormData("media_1", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), yourString);
Call<JSONObject> call = apiService.getApi().createPost(
name,
body0,
body1,
body2,
body3,
body4,
secretKey
);
本质上,问题是我在 createFormData() 和 @Part 中声明了名称。你只能做其中之一。
我还将第一个参数更改为 RequestBody。如果你只是尝试使用一个字符串,至少在我的例子中,API 会认为它实际上应该有一个双引号。
该解决方案的链接:Retrofit 2.0-beta-2 is adding literal quotes to MultiPart values
关于java - 改造2 : Post multiple files with part names along with @FormUrlEncoded formData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355866/