Retrofit2 Upload Image And Other Data In Multipart

ApiServices apiServices = 
MultipartBody.Part body = null;
File file = new File(mFilePath);
RequestBody data = RequestBody.create(MediaType.parse(“image/*“), file);

body = MultipartBody.Part.createFormData(“image”, file.getName(), data);
RequestBody description = 
RequestBody.create(MediaType.parse(“text/plain”),“Hello multipart”);
RequestBody sports_id = RequestBody.create(MediaType.parse(“text/plain”),“2”);
RequestBody location = RequestBody.create(MediaType.parse(“text/plain”), “New Delhi”);
String auth_token =  ((MainActivity)getActivity()).appSharedPreference.getAuthToken() ;

Call<JsonElement> call = apiservices.postMoment(auth_token , description, sports_id, location, body) ;
call.enqueue(new Callback<JsonElement>() {
       public void onResponse(retrofit2.Call<JsonElement> call, Response<JsonElement> response) {
           Log.e(TAG , “response: “+response.toString());

       public void onFailure(retrofit2.Call<JsonElement> call, Throwable t) {
           Log.e(TAG , “error: “+t.getMessage());

API Interface:

Call<JsonElement> postMoment(
    @Header("X-User-Token")String access_token,
    @Part("description") RequestBody description,
    @Part("sport_id") RequestBody sport_id,
    @Part("location") RequestBody location
    @Part MultipartBody.Part image,


But, how do I want to ENCAPSULATE all these parameter into one "moment". Such as we do while creating Json Object

   moment : 
{  “description” : “<Description string>”  , 
    “sports_id”: “<sports_id>” ,
    “location”:   “<location>”


My request to api interface should be like:

Call<JsonElement> call = apiservices.postMoment(auth_token, single_parameter) ;

In that single parameter, all fields to be encapsulate. I tried Map but couldn't combine whole data into single string called "moment".

Any help would be appreciated. Thanks



Please try this, you can create pojo class for your request

Call<JsonElement> postMoment(
    @Header("X-User-Token")String access_token,
    @Body RequestMoment moment,


public class RequestMoment {
    public Moment moment;
    public class Moment {
        public Moment(RequestBody description, RequestBody sport_id, 
                      RequestBody location, MultipartBody.Part image){
            this.description = description;
            this.sport_id = sport_id;
            this.location = location;
            this.image = image;
        public RequestBody description;
        public RequestBody sport_id;
        public RequestBody location;
        public MultipartBody.Part image;

API call

Moment moment = new Moment(description, sports_id, location, body);
Call<JsonElement> call = apiservices.postMoment(auth_token, moment);