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)
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 的数组
请注意:第一个链接指向曾经在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.
基于初始问题中的示例,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推出。
| 归档时间: |
|
| 查看次数: |
82475 次 |
| 最近记录: |