okhttp icon indicating copy to clipboard operation
okhttp copied to clipboard

Cannot add Content-Length header to a multipart part

Open jasonrobinson-gpsw opened this issue 1 month ago • 3 comments

In #7319 the Content-Length header ceased being auto-included in every multipart part. That is fine, but manually adding that header to a part throws an exception:

MultipartBody.Part.create(
    headers = Headers.Builder().add("Content-Length", TEST_DATA.size.toString()).build(),
    body = TEST_DATA.toRequestBody(),
) // crash - "Unexpected header: Content-Length"

The crash is due to this line in the MultipartBody.Part.create method:

require(headers?.get("Content-Length") == null) { "Unexpected header: Content-Length" }

I think that require was added because that header was being auto-included at the time. Since that is no longer the case but the require still exists, it's impossible to add a Content-Length header using the factory method.

I believe including Content-Length on a multipart part is out-of-spec if the request is of type multipart/form-data, but is within RFC specs for other types like multipart/mixed.

Tests showing it's not possible to manually include Content-Length: https://gist.github.com/jasonrobinson-gpsw/830a56b81be94a704fad9409d8326865

jasonrobinson-gpsw avatar Oct 23 '26 22:10 jasonrobinson-gpsw

Hello, If possible i would like to work on this.

alexzargarian23 avatar Oct 24 '26 10:10 alexzargarian23

is the goal to sent it even when out of spec? or just to be able to send for the other types you mention?

yschimke avatar Nov 14 '26 16:11 yschimke

is the goal to sent it even when out of spec? or just to be able to send for the other types you mention?

My requirement is only for multipart/mixed (within spec).

jasonrobinson-gpsw avatar Nov 16 '26 18:11 jasonrobinson-gpsw