Skip to content

Commit

Permalink
Fix sttp client content-type header override (#3472)
Browse files Browse the repository at this point in the history
  • Loading branch information
markarasev authored Jan 24, 2024
1 parent 39bd00a commit 27b1b1a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,10 @@ private[sttp] class EndpointToSttpClient[R](clientOptions: SttpClientOptions, ws
codec: Codec[L, H, CF],
req: PartialAnyRequest
): PartialAnyRequest = {
// If true, Content-Type header was explicitly set, so the body's default value
// or the codec's media type should not override it.
val wasContentTypeAlreadySet = req.header(HeaderNames.ContentType).nonEmpty

val encoded = codec.encode(v)
val req2 = bodyType match {
case RawBodyType.StringBody(charset) => req.body(encoded, charset.name())
Expand All @@ -185,7 +189,7 @@ private[sttp] class EndpointToSttpClient[R](clientOptions: SttpClientOptions, ws
req.multipartBody(parts.toList)
}

req2.contentType(codec.format.mediaType)
if (wasContentTypeAlreadySet) req2 else req2.contentType(codec.format.mediaType)
}

private def partToSttpPart[T](p: Part[T], bodyType: RawBodyType[T]): Part[RequestBody[Any]] =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,22 @@ class SttpClientRequestTests extends AnyFunSuite with Matchers {
uri(Some(true)).toString shouldBe "http://localhost?flag"
uri(Some(false)).toString shouldBe "http://localhost?flag=false"
}

test("dynamic content-type header shouldn't be overridden by body's default one") {
// given
val testEndpoint = endpoint
.in("test")
.post
.in(header[String](HeaderNames.ContentType))
.in(byteArrayBody)

// when
val sttpClientRequest = SttpClientInterpreter()
.toRequest(testEndpoint, None)
.apply(("image/jpeg", Array.empty))

// then
val actual = sttpClientRequest.headers.find(_.is(HeaderNames.ContentType)).get.value
actual shouldEqual "image/jpeg"
}
}

0 comments on commit 27b1b1a

Please sign in to comment.