如何从 HttpClient 获取 Cookie?

2022-08-31 23:57:49

我使用的是 HttpClient 4.1.2

HttpGet httpget = new HttpGet(uri); 
HttpResponse response = httpClient.execute(httpget);

那么,如何获取 Cookie 值呢?


答案 1

不知道为什么接受的答案描述了一个不存在的方法。这是不正确的。getCookieStore()

您必须事先创建一个 Cookie 存储,然后使用该 Cookie 存储构建客户端。然后,您可以稍后参考此 Cookie 存储以获取 Cookie 列表。

/* init client */
HttpClient http = null;
CookieStore httpCookieStore = new BasicCookieStore();
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);
http = builder.build();

/* do stuff */
HttpGet httpRequest = new HttpGet("http://stackoverflow.com/");
HttpResponse httpResponse = null;
try {httpResponse = http.execute(httpRequest);} catch (Throwable error) {throw new RuntimeException(error);}

/* check cookies */
httpCookieStore.getCookies();

答案 2

又一个让其他人开始,看到不存在的方法挠挠头......

import org.apache.http.Header;
import org.apache.http.HttpResponse;

Header[] headers = httpResponse.getHeaders("Set-Cookie");
for (Header h : headers) {
    System.out.println(h.getValue().toString());  
}

这将打印 Cookie 的值。服务器响应可以有多个标头字段,因此您需要检索一个数组Set-CookieHeader


推荐