Java – How do I convert Map to RequestBody?

How do I convert Map to RequestBody?… here is a solution to the problem.

How do I convert Map to RequestBody?

With Retrofit 2.4.0, I’m working on @Multipart @POST requirements. I send the file as @Part along with some metadata as @PartMap. This is what the call looks like.

@Multipart
@POST("https://8hoot.com/my-path")
Single<Response<UploadMediaResponseModel>> uploadMedia(
        @PartMap Map<String, RequestBody> metadata,
        @Part MultipartBody.Part filePart
);

There is also a Map<String, String>, let’s call it a subMetaMap, which contains the relevant key-value pairs.

How do I store this subMetaMap in @PartMap metadata?

RequestBody subMetaMapAsRequestBody;  Convert subMetaMap to RequestBody
metadata.put("subMeta", subMetaMapAsRequestBody);

Currently, I am using the following method.

for (String s : subMetaMap.keySet()) {
    RequestBody requestBody = RequestBody.create(MultipartBody.FORM, subMetaMap.get(s));
    metadata.put(s, requestBody);
}

This is not the solution I want, because I want the entire subMetaMap as a RequestBody not its individual key-value pairs


Edit 1– The backend team does not adopt different MIME type requirements during Multipart. So sending JSON, MessagePack, etc. is not an option.

Solution

Suppose you have the following map and you want to send this data to the body of the transformation request

HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");

The URL request method is as follows:

@FormUrlEncoded
@POST("/yourapiname")
Call<ResponseObj> methodName(@FieldMap HashMap<String, String> yourHasMapObject);

If you want to add files and hashmaps then use the following method:

@Multipart
@POST("yourapiname")
Call<ResponseObj> methodName(@HeaderMap HashMap<String, String> yourHasMapObject, @Part MultipartBody.Part file);

Related Problems and Solutions