Apache HttpClient是否将java.net.CookieHandler设置的Cookie添加到Request中?
我的简单 Apache HttpClient (4.0.1) 客户端应用程序在 main() 方法中向服务器 URL 发出 HttpGet 请求并打印响应。启动时,应用程序在静态块中注册 java.net.CookieHandler 的实现。
在检查服务器端收到的 cookie 时,我发现当 HttpClient 发出 GET 请求时,服务器没有收到 cookie。
另一方面,当我用普通的 java.net.URL(HTTP_URL).openStream() 替换 Apache HttpClient 时,cookie 由请求上的 CookieHandler 设置并由服务器接收。
CookieHandler 是否不能与 Apache HttpClient 一起使用?
代码:
Client.java
static { CookieHandler.setDefault(new CookieHandler() { public Map get(URI u, List r) { return Collections.singletonMap("Cookie", Collections.singletonList(COOKIE_STRING)); } }); }
使用 HttpClient (不根据请求放置 cookie)
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(HTTP_URL); client.execute(get);
使用 java.net.URL (根据请求设置 cookie)
URL url = new URL(HTTP_URL); InputStream is = url.openStream();
My simple Apache HttpClient (4.0.1) client application makes an HttpGet request to a server URL in the main() method and prints the response. On startup, the application registers an implementation of java.net.CookieHandler in a static block.
On checking the cookies received on the server side, I found that the cookies are not being received by the Server when the HttpClient makes the GET request.
On the other hand, when I replaced the Apache HttpClient with a plain java.net.URL(HTTP_URL).openStream(), the cookies were set by the CookieHandler on the Request and were received by the Server.
Is it that CookieHandler does not work with Apache HttpClient?
Code:
Client.java
static { CookieHandler.setDefault(new CookieHandler() { public Map get(URI u, List r) { return Collections.singletonMap("Cookie", Collections.singletonList(COOKIE_STRING)); } }); }
Using HttpClient (does not put cookies on request)
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(HTTP_URL); client.execute(get);
Using java.net.URL (sets the cookies on request)
URL url = new URL(HTTP_URL); InputStream is = url.openStream();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的。
Apache HttpClient 代码库使用自己的 cookie 和 cookie 存储表示/机制。以下是 HttpClient 教程<的相关部分的链接/a>. (这是相当粗略的,但是如果您查看相关类的 javadoc,您应该能够弄清楚如何使用它。)
(如果您使用的是较旧版本的 Apache HttpClient,请注意 API 已发生显着变化.)
That is correct.
The Apache HttpClient codebase uses its own cookie and cookie store representations / mechanisms. Here is a link to the relevant section of the HttpClient tutorial. (It is pretty sketchy, but if you look at the javadocs for the relevant classes, you should be able to figure out how to use it.)
(If you are using an older version of Apache HttpClient, beware that the APIs have changed significantly.)