@Multipart
@POST("/api/add-deal/")
public void addDeal(@Body Deal deal, @Part("image")TypedFile image,Callback<Response> callback);
我只想将图像作为多部分发送,其余部分按原样发送。有什么可能的方法吗?即使我尝试在我的 Deal 模型中添加 TypedFile 但无法使用 @part 进行注释
最佳答案
是的,使用散列映射的 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);
希望这对您有所帮助。
关于android - 是否可以使用改造将单个项目作为多部分传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998828/