使用 HttpComponents 的 HttpClient 包来访问 WordPress 的登录页面,有如下的警告信息
2011-12-16 22:15:37 org.apache.http.client.protocol.ResponseProcessCookies processCookies警告: Cookie rejected: "[version: 0][name: wordpress_0f6656bfca67cbc6623cf00ad16ac695][value: ld%7C1324217627%7C291f724c73c12859ae871c3b51bea61a][domain: blog.makingware.com][path: /wp-content/plugins][expiry: null]". Illegal path attribute "/wp-content/plugins". Path of origin: "/"
2011-12-16 22:15:37 org.apache.http.client.protocol.ResponseProcessCookies processCookies警告: Cookie rejected: "[version: 0][name: wordpress_0f6656bfca67cbc6623cf00ad16ac695][value: ld%7C1324217627%7C291f724c73c12859ae871c3b51bea61a][domain: blog.makingware.com][path: /wp-admin][expiry: null]". Illegal path attribute "/wp-admin". Path of origin: "/"
代码如下:
private final static DefaultHttpClient client = new DefaultHttpClient(); static { client.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); }
试遍了 CookiePolicy 中的所有常量值都无效,除了那个 IGNORE_COOKIES
好像这是一个bug,我用的是 4.1.2 版本,这是 HttpClient 最新的 GA 版本。
还有什么其他办法能让 HttpComponents 接受 WordPress 的 Cookie 呢?
找到了解决的办法!!!
private final static DefaultHttpClient client = new DefaultHttpClient(); static { CookieStore cookieStore = new BasicCookieStore(); //Bind custom cookie store to the local context client.setCookieStore(cookieStore); CookieSpecFactory csf = new CookieSpecFactory() { public CookieSpec newInstance(HttpParams params) { return new BrowserCompatSpec() { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { // Oh, I am easy // allow all cookies //log.debug("custom validate"); } }; } }; client.getCookieSpecs().register("oschina", csf); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, "oschina"); client.getParams().setParameter(CookieSpecPNames.SINGLE_COOKIE_HEADER, true); }
耶!
######版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。