decodeRequest

Signature

def decodeRequest: Directive0

Description

Decompresses the incoming request if it is gzip or deflate compressed. Uncompressed requests are passed through untouched. If the request encoded with another encoding the request is rejected with an UnsupportedRequestEncodingRejectionUnsupportedRequestEncodingRejection. If the request entity after decoding exceeds akka.http.routing.decode-max-size the stream fails with an akka.http.scaladsl.model.EntityStreamSizeException.

Example

Scala
val route =
  decodeRequest {
    entity(as[String]) { content: String =>
      complete(s"Request content: '$content'")
    }
  }

// tests:
Post("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'Hello'"
}
Post("/", helloDeflated) ~> `Content-Encoding`(deflate) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'Hello'"
}
Post("/", "hello uncompressed") ~> `Content-Encoding`(identity) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'hello uncompressed'"
}
Java
final ByteString helloGzipped = Coder.Gzip.encode(ByteString.fromString("Hello"));
final ByteString helloDeflated = Coder.Deflate.encode(ByteString.fromString("Hello"));

final Route route = decodeRequest(() ->
  entity(entityToString(), content ->
    complete("Request content: '" + content + "'")
  )
);

// tests:
testRoute(route).run(
  HttpRequest.POST("/").withEntity(helloGzipped)
    .addHeader(ContentEncoding.create(HttpEncodings.GZIP)))
  .assertEntity("Request content: 'Hello'");

testRoute(route).run(
  HttpRequest.POST("/").withEntity(helloDeflated)
    .addHeader(ContentEncoding.create(HttpEncodings.DEFLATE)))
  .assertEntity("Request content: 'Hello'");

testRoute(route).run(
  HttpRequest.POST("/").withEntity("hello uncompressed")
    .addHeader(ContentEncoding.create(HttpEncodings.IDENTITY)))
  .assertEntity( "Request content: 'hello uncompressed'");
The source code for this page can be found here.