简体   繁体   中英

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

在此处输入图片说明

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

Following is the code

@Multipart
@POST("/some-api-method")
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

@Multipart
@POST("/some-api-method")
@Headers({
        "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 & https://stackoverflow.com/a/51647665/932044 these pointed me in the right direction and i have fixed my issue in the following way

 @POST("/some-api-method")
 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))
       .build();
String contentType = "multipart/form-data; charset=utf-8; boundary=" + multipartBody.boundary();
        
someCreateMethod(contentType, multipartBody);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM