【问题标题】:is it possible to pass a single item as multipart using retrofit?是否可以使用改造将单个项目作为多部分传递?
【发布时间】:2017-08-17 08:27:11
【问题描述】:
@Multipart
@POST("/api/add-deal/")
public void addDeal(@Body Deal deal, @Part("image")TypedFile image,Callback<Response> callback);
我只想将图像作为多部分发送,其余部分按原样发送。有什么可能的方法吗?即使我尝试在我的 Deal 模型中添加 TypedFile 但无法使用 @part 进行注释
【问题讨论】:
标签:
android
retrofit
multipart
【解决方案1】:
是的,Partmap 注释可以使用哈希映射。例如-
@Multipart
@POST("/api/add-deal/")
Call<Response> addDeal(@PartMap
HashMap<String, RequestBody> hashMap);
在 hashMap 中,您可以不添加任何 url 参数作为键,并使用 RequestBody 类类型设置您的值。看看如何将 String 和 Image 转换为 RequestBody。
public static RequestBody ImageToRequestBody(File file) { //for image file to request body
return RequestBody.create(MediaType.parse("image/*"),file);
}
public static RequestBody StringToRequestBody(String string){ // for string to request body
return RequestBody.create(MediaType.parse("text/plain"),string);
}
将参数添加到 hashmap-
hashMap.put("photo",ImageToRequestBody(imageFile)); //your imageFile to Request body.
hashMap.put("user_id",StringToRequestBody("113"));
//calling addDeal method
apiInterface.addDeal(hashMap);
希望这有帮助。
【解决方案2】:
看来您可以将 @Body 作为 TypedString 发送。
例如,将您的“@Body Deal deal”转换为 JSON 字符串,并将其作为 TypedString 发送。
详情:How to send multipart/form-data with Retrofit?
@Multipart
@POST("/api/v1/articles/")
Observable<Response> uploadFile(@Part("author") TypedString authorString,
@Part("photo") TypedFile photoFile);
【解决方案3】:
这对我有用:POST Multipart Form Data using Retrofit 2.0 including image
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("FirstName") RequestBody fname, @Part("Id") RequestBody id);
}
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Call<User> call = client.editUser(AZUtils.getToken(this), fbody, name, id);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit) {
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});