[英]I want to get data from service using retrofit, how can I achieve this in android?
[英]I want to pass json object as a raw data using @Body in retrofit, but I am unable to add an image file inside the Request Object, how can I achieve it
我需要传递的 JSON 格式的数据是:
{
"user":{
"email":"xxxx",
"password":"xxxx",
"first_name":"XXXX",
"last_name":"XXXX",
"date_of_birth":"XXXX",
"image":"myFile.jpg",
"location":"XXXX",
"my_list1":[
{
"first_name":"XXXX",
"last_name":"XXXX",
"telephone_number":"XXXX"
},
{
"first_name":"XXXX",
"last_name":"XXXX",
"telephone_number":"XXXX"
}
],
"my_list2":[
{
"id":"1"
},
{
"id":"2"
}
]
}
}
使用时我无法在 mainRequestObj 中添加图像:
@POST("users")
Call<MainResponse> register(@Header("abc") String abc,@Body MainRequestObj mainRequestObj);
有什么方法可以将图像作为原始正文格式的文件传递? 我正在使用 retrofit 2.9.0。 提前致谢!
您必须为您的POST
API 使用表单数据,然后您就可以实现这一点。 您还必须从后端开发人员那里获得一些帮助。 检查下面的示例代码。 试试这个方法,让我知道你的发现
@Multipart
@POST("expenses/upload")
Observable<UploadExpensesWithImageResponse> uploadExpensesWithImageAPI(
@Header("Authorization") String accessToken,
@Part MultipartBody.Part[] picture,
@Part("store_id") RequestBody store_id,
@Part("amount") RequestBody amount,
@Part("expense_date") RequestBody expense_date);
您可以将 bitmap 转换为 base64 字符串并将其发送到服务器。
但是您应该发送多部分请求。 当我阅读您的评论时,有一个您想要发送到服务器的对象列表。 您应该创建一个包含数据列表的 POJO,然后将其与多部分请求一起发送。
这是一些代码示例:
class SyncUpData {
@SerializedName("Products")
var products: List<ProductDTO>? = null
@SerializedName("ProductTax")
var productTax: List<ProductTaxDTO>? = null
}
并与您的多部分请求一起执行以下操作:
val str = GsonBuilder().create().toJson(syncUpObj)
val jsonObject: JSONObject = JSONObject(str)
val body = jsonObject.toString(1)
val syncUp = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), body)
您的 API 致电:
@Multipart
@POST("")
Call<ResponseDTO> syncUpNow(@Part MultipartBody.Part[] images,
@Part("syncUp") RequestBody myObj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.