|
| 1 | +package com.baeldung.httpclient.cookies; |
| 2 | + |
| 3 | +import org.apache.http.client.CookieStore; |
| 4 | +import org.apache.http.client.methods.CloseableHttpResponse; |
| 5 | +import org.apache.http.client.methods.HttpGet; |
| 6 | +import org.apache.http.client.protocol.HttpClientContext; |
| 7 | +import org.apache.http.cookie.Cookie; |
| 8 | +import org.apache.http.impl.client.BasicCookieStore; |
| 9 | +import org.apache.http.impl.client.CloseableHttpClient; |
| 10 | +import org.apache.http.impl.client.HttpClients; |
| 11 | +import org.apache.http.impl.cookie.BasicClientCookie; |
| 12 | +import org.junit.Test; |
| 13 | +import org.slf4j.Logger; |
| 14 | +import org.slf4j.LoggerFactory; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | + |
| 18 | +import static org.junit.Assert.assertEquals; |
| 19 | + |
| 20 | + |
| 21 | +public class HttpClientGettingCookieValueUnitTest { |
| 22 | + private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class); |
| 23 | + |
| 24 | + private static final String SAMPLE_URL = "http://www.baeldung.com/"; |
| 25 | + |
| 26 | + @Test |
| 27 | + public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException { |
| 28 | + HttpClientContext context = HttpClientContext.create(); |
| 29 | + context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore()); |
| 30 | + |
| 31 | + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { |
| 32 | + try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) { |
| 33 | + CookieStore cookieStore = context.getCookieStore(); |
| 34 | + Cookie customCookie = cookieStore.getCookies() |
| 35 | + .stream() |
| 36 | + .peek(cookie -> log.info("cookie name:{}", cookie.getName())) |
| 37 | + .filter(cookie -> "custom_cookie".equals(cookie.getName())) |
| 38 | + .findFirst() |
| 39 | + .orElseThrow(IllegalStateException::new); |
| 40 | + |
| 41 | + assertEquals("test_value", customCookie.getValue()); |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + private BasicCookieStore createCustomCookieStore() { |
| 47 | + BasicCookieStore cookieStore = new BasicCookieStore(); |
| 48 | + BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value"); |
| 49 | + cookie.setDomain("baeldung.com"); |
| 50 | + cookie.setPath("/"); |
| 51 | + cookieStore.addCookie(cookie); |
| 52 | + return cookieStore; |
| 53 | + } |
| 54 | +} |
0 commit comments