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.

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'");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.