From 2f8478db349260fc51b143972b72367af579a3c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20G=C5=82=C3=B3wka?= Date: Tue, 29 Sep 2020 19:12:16 +0200 Subject: [PATCH] BAEL-4446: Getting cookies from httpclient response example (#10104) --- .../HttpClientGettingCookieValueUnitTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java diff --git a/httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java b/httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java new file mode 100644 index 0000000000..c3b0ef3c25 --- /dev/null +++ b/httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java @@ -0,0 +1,54 @@ +package com.baeldung.httpclient.cookies; + +import org.apache.http.client.CookieStore; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.cookie.BasicClientCookie; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + + +public class HttpClientGettingCookieValueUnitTest { + private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class); + + private static final String SAMPLE_URL = "http://www.baeldung.com/"; + + @Test + public final void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException { + HttpClientContext context = HttpClientContext.create(); + context.setAttribute(HttpClientContext.COOKIE_STORE, createCustomCookieStore()); + + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + try (CloseableHttpResponse response = httpClient.execute(new HttpGet(SAMPLE_URL), context)) { + CookieStore cookieStore = context.getCookieStore(); + Cookie customCookie = cookieStore.getCookies() + .stream() + .peek(cookie -> log.info("cookie name:{}", cookie.getName())) + .filter(cookie -> "custom_cookie".equals(cookie.getName())) + .findFirst() + .orElseThrow(IllegalStateException::new); + + assertEquals("test_value", customCookie.getValue()); + } + } + } + + private BasicCookieStore createCustomCookieStore() { + BasicCookieStore cookieStore = new BasicCookieStore(); + BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value"); + cookie.setDomain("baeldung.com"); + cookie.setPath("/"); + cookieStore.addCookie(cookie); + return cookieStore; + } +}