问题
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