Request Values: Headers
A collection of pre-defined Request values that can be used to extract header values from incoming requests.
Description
Header request values allow extracting HttpHeader values or concrete instances from HTTP requests.
The RequestVal builder is made up of 2 steps, initially you need to pick which Header to extract (byName or byClass) and then you need to pick if the header is optionally available or required (i.e. the route should not match if the header is not present in the request). This is done using one of the below depicted methods:
RequestVal<T> instance()
RequestVal<<Optional<T>> optionalInstance()
RequestVal<String> value()
RequestVal<Optional<String>> optionalValue()
Examples
Extracting a header by using a specific Header class (which are pre-defined in akka.http.javadsl.model.headers.*):
// extract the entire header instance:
RequestVal<Host> host = Headers.byClass(Host.class).instance();
final Route route =
route(
handleWith1(host, (ctx, h) ->
ctx.complete(String.format("Host header was: %s", h.host()))
)
);
// tests:
final HttpRequest request =
HttpRequest
.GET("http://akka.io/")
.addHeader(Host.create("akka.io"));
testRoute(route).run(request).assertEntity("Host header was: akka.io");
Extracting arbitrary headers by their name, for example custom headers (usually starting with X-...):
// extract the `value` of the header:
final RequestVal<String> XFishName = Headers.byName("X-Fish-Name").value();
final Route route =
route(
handleWith1(XFishName, (ctx, xFishName) ->
ctx.complete(String.format("The `X-Fish-Name` header's value was: %s", xFishName))
)
);
// tests:
final HttpRequest request =
HttpRequest
.GET("/")
.addHeader(RawHeader.create("X-Fish-Name", "Blippy"));
testRoute(route).run(request).assertEntity("The `X-Fish-Name` header's value was: Blippy");
Contents