Android Retrofit使用Multipart注解时如何发送自定义对象
问题解答
@Multipart 模式下 Retrofit 不允许同时使用 @Body 注解,你可以将 User 对象转换为以下两种支持的类型完成请求发送:
方案1:将 User 对象序列化为 JSON 后封装为 RequestBody
- 实现逻辑:通过 Gson/Jackson 等 JSON 序列化工具将 User 实例转为 JSON 字符串,再把字符串包装为
RequestBody,通过@Part注解传递 - 修改后接口示例:
@Multipart @POST("drivers") Call<JSONObject> addANewUser( @Part("user") RequestBody user, @Part("licenceFrontPicture") RequestBody licenceFrontPicture, @Part("licenceBackPicture") RequestBody licenceBackPicture, @Part("idCardFrontPicture") RequestBody idCardFrontPicture, @Part("idCardBackPicture") RequestBody idCardBackPicture );
- 调用时构造 User 对应 RequestBody 的代码示例:
// 序列化User为JSON字符串 Gson gson = new Gson(); String userJson = gson.toJson(userInstance); // 封装为RequestBody,指定媒体类型为JSON RequestBody userRequestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), userJson); // 调用接口时传入即可 api.addANewUser(userRequestBody, licenceFront, licenceBack, idFront, idBack);
注意:该方案需要后端接口对应接收user字段为JSON格式的参数
方案2:将 User 对象的字段拆分后单独用 @Part 传递
如果后端不支持接收JSON格式的User参数,你可以把User的每个属性单独拆成@Part参数传递,示例如下:
@Multipart @POST("drivers") Call<JSONObject> addANewUser( @Part("name") RequestBody name, @Part("age") Integer age, @Part("phone") RequestBody phone, @Part("licenceFrontPicture") RequestBody licenceFrontPicture, @Part("licenceBackPicture") RequestBody licenceBackPicture, @Part("idCardFrontPicture") RequestBody idCardFrontPicture, @Part("idCardBackPicture") RequestBody idCardBackPicture );
如果字段是基础数据类型,也可以直接传入对应类型,不需要封装为RequestBody,Retrofit会自动处理
内容的提问来源于stack exchange,提问作者Mohamad Nidal
相关产品推荐
相关产品推荐

