Skip to content

Update default Content-Type for multipart form-data request in Android

We are currently using okhttp3 and retrofit2 in Android to make an network api call of type POST with multipart/form-data, the api request and response are as shown below

enter image description here

If you observe, the request header Content-Type has “multipart/form-data; boundary=xxxxxx-xxxx-xxx....

Following is the code

Call<SomeResponseBody> someCreateMethod(@PartMap Map<String, RequestBody> options);

I’m facing an issue with sending the customised request header Content-Type as “multipart/form-data; **charset=utf-8;** boundary=xxxxx-xxxxx-x.....” basically i need to update the Content-Type header to accommodate “charset=utf-8;” For this i tried following code

        "Content-Type: multipart/form-data; charset=utf-8"
Call<SomeResponseBody> someCreateMethod(@PartMap Map<String, RequestBody> options);

This resulted in addition of “charset=utf-8;” to Content-Type, but this resulted in removal or non addition of existing attribute “boundary=xxx-xxxx.....;

basically i need something like below

Content-Type : "multipart/form-data; charset=utf-8; boundary=xxxx-xxx.....;"

Any help here to achieve this will be appreciated.



Thanks to Retrofit – Multipart request: Required MultipartFile parameter ‘file’ is not present & these pointed me in the right direction and i have fixed my issue in the following way

 Call< SomeResponseBody > someCreateMethod(@Header("Content-Type") String contentType, @Body RequestBody body);

I created the MultipartBody object as below

RequestBody dataBody = RequestBody.create(okhttp3.MultipartBody.FORM, mGson.toJson(mData));
MultipartBody multipartBody = new MultipartBody.Builder()
       .addPart(MultipartBody.Part.createFormData("key1", null, requestBodyObj1))
       .addPart(MultipartBody.Part.createFormData("key2", null, requestBodyObj2))
       .addPart(MultipartBody.Part.createFormData("key3", null, dataBody))
String contentType = "multipart/form-data; charset=utf-8; boundary=" + multipartBody.boundary();
someCreateMethod(contentType, multipartBody);
User contributions licensed under: CC BY-SA
4 People found this is helpful