简体   繁体   中英

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

Data in JSON format I need to pass is:

{
   "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"
         }
      ]
   }
}

I can not add an image in mainRequestObj while using:

@POST("users")
Call<MainResponse> register(@Header("abc") String abc,@Body MainRequestObj mainRequestObj);

Is there any way I can pass the image as a file in the raw body format? I am using retrofit 2.9.0. Thanks in advance!

You have to use form data for your POST API then you can achieve this. you have to get some help from your back-end developer as well. check this below example code. Try this way and let me know your finding

@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);

在此处输入图像描述

You can convert your bitmap into a base64 string and send it to the server.

But you should send the multipart request. As I read your comment there is a list of objects that you want to send to the server. You should create a POJO that contains your list of data and then send it along with the multipart request.

Here is some code example:

class SyncUpData {
@SerializedName("Products")
var products: List<ProductDTO>? = null

@SerializedName("ProductTax")
var productTax: List<ProductTaxDTO>? = null
}

And along with your multipart request do like this:

    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)

Your API Call:

@Multipart
@POST("")
Call<ResponseDTO> syncUpNow(@Part MultipartBody.Part[] images,
                                        @Part("syncUp") RequestBody myObj

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM