Skip to content

Commit 4cc8427

Browse files
committed
OkHttp
1 parent e793de3 commit 4cc8427

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

okhttp-backend/src/main/scala/sttp/client4/okhttp/OkHttpBackend.scala

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ import sttp.client4._
2222
import sttp.model._
2323

2424
import scala.collection.JavaConverters._
25+
import sttp.client4.compression.Compressor
26+
import sttp.client4.compression.DeflateDefaultCompressor
27+
import sttp.client4.compression.GZipDefaultCompressor
2528

2629
abstract class OkHttpBackend[F[_], S <: Streams[S], P](
2730
client: OkHttpClient,
@@ -33,6 +36,8 @@ abstract class OkHttpBackend[F[_], S <: Streams[S], P](
3336
val streams: Streams[S]
3437
type R = P with Effect[F]
3538

39+
protected val compressors: List[Compressor[R]] = List(new GZipDefaultCompressor(), new DeflateDefaultCompressor)
40+
3641
override def send[T](request: GenericRequest[T, R]): F[Response[T]] =
3742
adjustExceptions(request.isWebSocket, request) {
3843
if (request.isWebSocket) {
@@ -54,7 +59,8 @@ abstract class OkHttpBackend[F[_], S <: Streams[S], P](
5459
val builder = new OkHttpRequest.Builder()
5560
.url(request.uri.toString)
5661

57-
val body = bodyToOkHttp(request.body, request.contentType, request.contentLength)
62+
val (maybeCompressedBody, contentLength) = Compressor.compressIfNeeded(request, compressors)
63+
val body = bodyToOkHttp(maybeCompressedBody, request.contentType, contentLength)
5864
builder.method(
5965
request.method.method,
6066
body.getOrElse {
@@ -64,7 +70,13 @@ abstract class OkHttpBackend[F[_], S <: Streams[S], P](
6470
}
6571
)
6672

67-
request.headers.foreach(header => builder.addHeader(header.name, header.value))
73+
// the content-length header's value might have changed due to compression
74+
request.headers.foreach(header =>
75+
if (!header.is(HeaderNames.ContentLength)) {
76+
val _ = builder.addHeader(header.name, header.value)
77+
}
78+
)
79+
contentLength.foreach(cl => builder.addHeader(HeaderNames.ContentLength, cl.toString))
6880

6981
builder.build()
7082
}

0 commit comments

Comments
 (0)