/** * Returns the value of the {@code 'Content-Type'} header. * * @return content-type if present */ public Optional<String> contentType() { return header(CONTENT_TYPE); }
/** * Returns the value of the {@code 'Content-Length'} header. * * @return content-length if present */ public Optional<Integer> contentLength() { return header(CONTENT_LENGTH).map(Integer::valueOf); }
@Test public void contentFromStringSetsContentLengthIfRequired() { HttpResponse response1 = HttpResponse.response() .body("Response content.", UTF_8, true) .build(); assertThat(response1.header("Content-Length"), is(Optional.of("17"))); HttpResponse response2 = HttpResponse.response() .body("Response content.", UTF_8, false) .build(); assertThat(response2.header("Content-Length"), is(Optional.empty())); }
@Test public void contentFromByteArraySetsContentLengthIfRequired() { HttpResponse response1 = HttpResponse.response() .body("Response content.".getBytes(UTF_16), true) .build(); assertThat(response1.body(), is("Response content.".getBytes(UTF_16))); assertThat(response1.header("Content-Length"), is(Optional.of("36"))); HttpResponse response2 = HttpResponse.response() .body("Response content.".getBytes(UTF_8), false) .build(); assertThat(response2.body(), is("Response content.".getBytes(UTF_8))); assertThat(response2.header("Content-Length"), is(Optional.empty())); }
@Test public void headerValuesAreCaseSensitive() { HttpResponse response = response(OK).header("Content-Type", "TEXT/PLAIN").build(); assertThat(response.header("content-type"), not(isValue("text/plain"))); }
@Test public void shouldNotFailToRemoveNonExistentContentLength() { HttpResponse response = HttpResponse.response().build(); HttpResponse chunkedResponse = response.newBuilder().setChunked().build(); assertThat(chunkedResponse.chunked(), is(true)); assertThat(chunkedResponse.header(CONTENT_LENGTH).isPresent(), is(false)); }
@Test public void supportsCaseInsensitiveHeaderNames() { HttpResponse response = response(OK).header("Content-Type", "text/plain").build(); assertThat(response.header("content-type"), isValue("text/plain")); }
@Test public void shouldRemoveContentLengthFromChunkedMessages() { HttpResponse response = HttpResponse.response().header(CONTENT_LENGTH, 5).build(); HttpResponse chunkedResponse = response.newBuilder().setChunked().build(); assertThat(chunkedResponse.chunked(), is(true)); assertThat(chunkedResponse.header(CONTENT_LENGTH).isPresent(), is(false)); }
@Test public void allowsModificationOfHeadersBasedOnBody() { HttpResponse response = HttpResponse.response() .body("foobar", UTF_8) .build(); assertThat(response.header("some-header"), isAbsent()); HttpResponse newResponse = response.newBuilder() .header("some-header", response.body().length) .build(); assertThat(newResponse.header("some-header"), isValue("6")); assertThat(newResponse.bodyAs(UTF_8), is("foobar")); }