How to add custom header to retrofit request body part?

江枫思渺然 提交于 2019-12-06 06:49:51

问题


So I am building a multipart request using retrofit and I want to add a custom header to one one of the part. I have tried a lot of things but nothing seems to be working.

The photo shows a body request that contains 4 parts. Each part contains a body and a header, what I want is to add a custom header to the selected part. How can I do that?


回答1:


So just to answer my own question, I create a part with an image and a custom header like this:

MultipartBody.Part body = MultipartBody.Part.create(
    Headers.of("Content-Disposition", "form-data; name=\"" + "namevalue" + "\";" + " filename=\"" + filenamevalue + "\"", custom_header_name, custom_header_value),
    RequestBody.create(MediaType.parse("image/jpeg"), multimedia.getMedia())
);



回答2:


Unfortunately, currently there is no way to add headers directly to the Part via Retrofit. You can construct each part yourself as a Okhttp3.MultipartBody.Part and pass that to retrofit as a @Part parameter. The downside is that you lose using retrofit's converters and have to convert your data into the part body yourself.

I submitted pull request to add a feature to allow it here.



来源:https://stackoverflow.com/questions/41164123/how-to-add-custom-header-to-retrofit-request-body-part

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!