Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrofit 2 dynamically set part parameter name

Can I dynamically set parameter name as a part of a multi-part request using retrofit 2, What I'm exactly looking for is

@Multipart
@POST(UPDATE_PROFILE)
Call<SignUp> sendUpdateProfileRequest(
            @Part("profile_img") RequestBody img_file,
            @Part("DYNAMIC_PARAM_NAME") RequestBody first_name,...);

where DYNAMIC_PARAM_NAME is like id_seller/id_buyer/id_buyer, rest of parameters and the request URL remains same.

while making call can i achieve such type of function in Activity or Fragment ?

like image 343
Hardik Kubavat Avatar asked Oct 15 '25 14:10

Hardik Kubavat


1 Answers

You can try Retrofit's @PartMap annotation instead of @Part. Just change the API interface like below,

@Multipart
@POST(UPDATE_PROFILE)
Call<SignUp> sendUpdateProfileRequest(
        @Part("profile_img") RequestBody img_file,
        @PartMap Map<String, RequestBody> params,  /* notice the change here */
        ...
);

And use it like so,

... // code
Map<String, RequestBody> params = new HashMap<>();

// prepare RequestBody
RequestBody someDataBody = ....;

// add it Map object
params.put("DYNAMIC_PARAM_NAME", someDataBody);

// pass it to request
FooApiInterface api = ....;

Call<FooResponse> call = api.sendUpdateProfileRequest(imageFile, params);
call.enqueue({/* implement response listener */});

That should do the trick for you.

like image 60
Shashanth Avatar answered Oct 17 '25 04:10

Shashanth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!