[英]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我们目前在Android中使用okhttp3和retrofit2进行POST类型的网络api调用,使用multipart/form-data,api请求和响应如下图
If you observe, the request header Content-Type has " multipart/form-data; boundary=xxxxxx-xxxx-xxx....
"如果您观察到,请求标头 Content-Type 具有“ 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我面临将自定义请求标头 Content-Type 作为“ multipart/form-data; **charset=utf-8;** boundary=xxxxx-xxxxx-x.....
”发送的问题,基本上我需要更新 Content-Type 标头以适应“ charset=utf-8;
”为此我尝试了以下代码
@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.....;
"这导致向 Content-Type 添加“ charset=utf-8;
”,但这导致删除或不添加现有属性“ 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感谢Retrofit - Multipart request:Required MultipartFile parameter 'file' is not present & https://stackoverflow.com/a/51647665/932044这些为我指明了正确的方向,我已通过以下方式解决了我的问题
@POST("/some-api-method")
Call< SomeResponseBody > someCreateMethod(@Header("Content-Type") String contentType, @Body RequestBody body);
I created the MultipartBody object as below我创建了 MultipartBody 对象如下
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.