encodeResponse

Signature

def encodeResponse: Directive0

Description

Encodes the response with the encoding that is requested by the client via the Accept-Encoding header or rejects the request with an UnacceptedResponseEncodingRejection(supportedEncodings).

The response encoding is determined by the rules specified in RFC7231.

If the Accept-Encoding header is missing or empty or specifies an encoding other than identity, gzip or deflate then no encoding is used.

Example

Scala
val route = encodeResponse { complete("content") }

// tests:
Get("/") ~> route ~> check {
  response should haveContentEncoding(identity)
}
Get("/") ~> `Accept-Encoding`(gzip, deflate) ~> route ~> check {
  response should haveContentEncoding(gzip)
}
Get("/") ~> `Accept-Encoding`(deflate) ~> route ~> check {
  response should haveContentEncoding(deflate)
}
Get("/") ~> `Accept-Encoding`(identity) ~> route ~> check {
  response should haveContentEncoding(identity)
}
Java
import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.encodeResponse;

    final Route route = encodeResponse(() -> complete("content"));

    // tests:
    testRoute(route).run(
      HttpRequest.GET("/")
        .addHeader(AcceptEncoding.create(HttpEncodings.GZIP))
        .addHeader(AcceptEncoding.create(HttpEncodings.DEFLATE))
    ).assertHeaderExists(ContentEncoding.create(HttpEncodings.GZIP));

    testRoute(route).run(
      HttpRequest.GET("/")
        .addHeader(AcceptEncoding.create(HttpEncodings.DEFLATE))
    ).assertHeaderExists(ContentEncoding.create(HttpEncodings.DEFLATE));

    // This case failed!
//    testRoute(route).run(
//      HttpRequest.GET("/")
//        .addHeader(AcceptEncoding.create(HttpEncodings.IDENTITY))
//    ).assertHeaderExists(ContentEncoding.create(HttpEncodings.IDENTITY));
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.