如何從Apache HttpClient響應中獲取Cookie

1.概述

在這個簡短的教程中,我們將看到如何從Apache HttpClient響應中獲取cookie。

首先,我們將展示如何使用HttpClient請求發送自定義cookie。然後,我們將看到如何從響應中獲取它。

請注意,此處提供的代碼示例基於HttpClient 4.3.x及更高版本,因此它們不適用於較早版本的API。

2.在請求中發送Cookie

在從響應中獲取Cookie之前,我們需要創建它並在請求中發送它:

BasicCookieStore cookieStore = new BasicCookieStore();

 BasicClientCookie cookie = new BasicClientCookie("custom_cookie", "test_value");

 cookie.setDomain("baeldung.com");

 cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

 cookie.setPath("/");

 cookieStore.addCookie(cookie);



 HttpClientContext context = HttpClientContext.create();

 context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);



 try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

 try (CloseableHttpResponse response = httpClient.execute(new HttpGet("http://www.baeldung.com/"), context)) {

 //do something with the response

 }

 }

首先,我們創建一個基本的cookie存儲和一個基本的cookie,其名稱為custom_cookie和值test_value 。然後,我們創建一個將保存cookie存儲HttpClientContext最後,我們將創建的上下文作為參數傳遞給execute()方法。

3.訪問Cookies

現在,我們已經在請求中發送了一個自定義cookie,讓我們看看如何從響應中讀取它:

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());

 }

 }

要從響應中獲取我們的自定義cookie,我們必須首先從context中獲取cookie存儲。然後,我們使用getCookies方法獲取cookie列表。然後,我們可以利用Java流對其進行迭代並蒐索我們的cookie。此外,我們記錄了商店中的所有cookie名稱:

[main] INFO cbhcHttpClientGettingCookieValueTest - cookie name:__cfduid

 [main] INFO cbhcHttpClientGettingCookieValueTest - cookie name:custom_cookie

4.結論

在本文中,我們學習瞭如何從Apache HttpClient響應中獲取cookie。