/** * Adds cookies into this response by adding "Set-Cookie" headers. * * @param cookies cookies * @return {@code this} */ public Builder addCookies(Collection<ResponseCookie> cookies) { requireNonNull(cookies); if (cookies.isEmpty()) { return this; } removeCookies(cookies.stream().map(ResponseCookie::name).collect(toList())); encode(cookies).forEach(cookie -> addHeader(SET_COOKIE, cookie)); return this; }
/** * Removes all cookies matching one of the supplied names by removing their "Set-Cookie" headers. * * @param names cookie names * @return {@code this} */ public Builder removeCookies(String... names) { return removeCookies(asList(names)); }
@Test public void removesCookiesInSameBuilder() { HttpResponse r1 = response() .addCookies(responseCookie("x", "x1").build()) .removeCookies("x") .build(); assertThat(r1.cookie("x"), isAbsent()); }
@Test public void removesCookies() { HttpResponse r1 = response() .addCookies(responseCookie("x", "x1").build(), responseCookie("y", "y1").build()) .build(); HttpResponse r2 = r1.newBuilder() .removeCookies("x") .removeCookies("foo") // ensure that trying to remove a non-existent cookie does not cause Exception .build(); assertThat(r2.cookies(), contains(responseCookie("y", "y1").build())); }