Skip to main content

Response Headers

Response headers are accessed through the following methods:

RestResponsegetHeader(String)ResponseHeadergetHeaders(String)ResponseHeader[]getFirstHeader(String)ResponseHeadergetLastHeader(String)ResponseHeadergetAllHeaders()ResponseHeader[]getStringHeader(String)StringcontainsHeader(String)boolean

Unlike RestResponse.getFirstHeader(String) and RestResponse.getLastHeader(String), the RestResponse.getHeader(String) method returns an empty ResponseHeader object instead of returning null.

This allows it to be used more easily in fluent calls.

Example
RestResponse res = client.get(URI).complete();
ResponseHeader header = res.getHeader("Location");

// See if response contains Location header.
boolean hasLocationHeader = header.isPresent();

// Get actual value if it exists.
String locationHeader1 = header.orElse("http://localhost");

// Converted to object.
URI locationHeader2 = header.as(URI.class).orElse(null);

The ResponseHeader class extends from the HttpClient Header class and provides several convenience methods:

ResponseHeaderisPresent()booleanasString()Stringas(Type,Type...)Tas(Class)TasMatcher(Pattern)MatcherasMatcher(String)MatcherasHeader(Class)BasicHeaderasStringHeader()BasicStringHeaderasIntegerHeader()BasicIntegerHeaderasLongHeader()BasicLongHeaderasDateHeader()BasicDateHeaderasCsvHeader()BasicCsvHeaderasEntityTagsHeader()BasicEntityTagsHeaderasStringRangesHeader()BasicStringRangesHeaderasUriHeader()BasicUriHeader

The ResponseHeader.schema(HttpPartSchema) method allows you to perform parsing of OpenAPI formats for header parts.

Example
// Parse the header "Foo: bar|baz".
List fooHeader = client
.get(URI)
.complete()
.getHeader("Foo").schema(T_ARRAY_PIPES).as(List.class, String.class);

Assertion methods are also provided for fluent-style calls:

ResponseHeaderassertString()FluentStringAssertionassertInteger()FluentIntegerAssertionassertLong()FluentLongAssertionassertZonedDateTime()FluentZonedDateTimeAssertion

Note how in the following example, the fluent assertion returns control to the RestResponse object after the assertion has been completed:

Example
// Assert the response content type is any sort of JSON.
String content = client.get(URI)
.run()
.getHeader("Content-Type").assertString().matchesSimple("application/json*")
.getContent().asString();