nested multipart request using retrofit

2019-06-12 08:04发布

I need to make a request which is in nested multipart data. I need to send image in multi part form data and other details should also be in multipart. My Json request is as follow:

{
  "emailId": "vision.jav@avenger.com",
  "phoneNumber": "7417385811",
  "profileImage": "image",
  "password": "12345678",
  "customerDetails": {
    "firstName": "vison",
    "lastName": "vision"
  },
  "addressDetails": {
    "city": "chicago",
    "province": "NY",
    "postalCode": "654987",
    "latitude": "28.52",
    "longitude": "77.54"
  },
  "userRole": {
    "role": "CUSTOMER"
  }
}

2条回答
我想做一个坏孩纸
2楼-- · 2019-06-12 08:30

For reference ,I am posting the answer. I don`t know how json object are being mapped at backend. Finally, I found the solution afer so many tries. Its working for me. For the above posted request , just use a dot(.) along with inner json object for making keys as Follows.

  1. For inserting data for firstName, Use "customerDetails.firstName" as key.
  2. similarly for last name use "customerDetails.lastName" as key .
查看更多
Evening l夕情丶
3楼-- · 2019-06-12 08:37

You have to create one POJO class like your json structure and set all values.

then

@Multipart
@POST("uploadData.php")
Call<ServerResponse> uploadFile(@PartMap Map<String, RequestBody> map,@Part MultipartBody.Part file);

then You have to use mapping option to send data to the server.

Map<String, RequestBody> map = new HashMap<>();
        map.put("PRODUCTID", RequestBody.create(MediaType.parse("text/plain"), ProductId));

MultipartBody.Part imageFile = null;
        try {
            File file = new File(Environment.getExternalStorageDirectory() + "/Download/Salty.png");
            if file != null) {                
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),
                        file);
                imageFile = MultipartBody.Part.createFormData("ImageFile", file.getName(), requestFile);
            }
        }
        catch (Exception ex)
        {
            Log.d("UploadStatus", "Multipart Image as exception occurs");
        }


ApiService uploadImage = ApiClient.getClient().create(ApiService.class);
    Call<ServerResponse> fileUpload = uploadImage.uploadFile(map,imageFile);
    fileUpload.enqueue(new Callback<ServerResponse>() {
            @Override
            public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
                Toast.makeText(MainActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
                Toast.makeText(MainActivity.this, "Success " + response.body().toString(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {
                Log.d("TAG", "Error " + t.getMessage());
            }
    });
查看更多
登录 后发表回答