如何从HttpClient获取cookie?

cof*_*fee 39 java cookies apache-httpclient-4.x

我正在使用HttpClient 4.1.2

HttpGet httpget = new HttpGet(uri); 
HttpResponse response = httpClient.execute(httpget);
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能获得cookie值?

Ale*_*lex 50

不确定为什么接受的答案描述了一个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();
Run Code Online (Sandbox Code Playgroud)

  • 接受的答案适用于以前版本的v4.这种方法适用于最新的方法. (3认同)
  • 你可以做得更简单:`CloseableHttpClient httpclient = httpClients.custom().setDefaultCookieStore(cookies).build();` (3认同)
  • 是的,这应该是公认的答案。我只是将旧的 httpclient(3.x 到 4.3)迁移到新的,这个答案真的很有帮助。 (2认同)

Kov*_*mre 13

另一个让其他人开始,看到不存在的方法摸不着头脑......

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());  
}
Run Code Online (Sandbox Code Playgroud)

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


mkr*_*kro 8

请注意:第一个链接指向曾经在HttpClient V3中工作的东西.在下面找到与V4相关的信息.

这应该回答你的问题

http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

以下内容与V4相关:

...此外,javadocs应包含有关cookie处理的更多信息

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html

这是httpclient v4的教程:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

这里有一些伪代码可以帮助(我希望它只基于文档):

HttpClient httpClient = new DefaultHttpClient();
// execute get/post/put or whatever
httpClient.doGetPostPutOrWhatever();
// get cookieStore
CookieStore cookieStore = httpClient.getCookieStore();
// get Cookies
List<Cookie> cookies = cookieStore.getCookies();
// process...
Run Code Online (Sandbox Code Playgroud)

请确保您阅读了ResponseProcessCookies和AbstractHttpClient的javadoc.

  • 这就是问题.我找不到方法`httpClient.getCookieStore();` (31认同)
  • org.apache.http.impl.client.AbstractHttpClient httpClient = new org.apache.http.impl.client.DefaultHttpClient()演员似乎允许你获取cookie商店 (2认同)

Yan*_*dis 6

基于初始问题中的示例,CookieStore执行HTTP请求后访问的方式是使用HttpContext执行状态对象。

HttpContext 将在执行请求后引用 cookie 存储(如果未在 HttpClientBuilder 中指定 CookieStore,则为新存储)。

HttpClientContext context = new HttpClientContext();
CloseableHttpResponse response = httpClient.execute(request, context);
CookieStore cookieStore = context.getCookieStore();
Run Code Online (Sandbox Code Playgroud)

这适用于httpcomponents-client:4.3+该时ClosableHttpClient推出。