在Android中,当使用Apache的HttpClient进行http连接时,若需要使用Cookie,则一般做法是:
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Bind custom cookie store to the local context
localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// To perform http get
HttpGet request = new HttpGet(url);
HttpResponse response = new DefaultHttpClient().execute(request, localContext);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity());
// log(result)
}
一般情况下cookie使用没问题,但是现在有许多大型网站,登陆验证在是不同的域(domain),这样就会导致cookie跨域不可写的问题。搜索了一下发现还挺难找解决方案的,最后还是在stackoverflow上发现的。 Java HtmlUnit - can't login to wordpress
其实apache的文档已经说明了这个问题了,请看这里:Chapter 3. HTTP state management 拉到下边,例子都给出来了。
做法就是自己重写cookie策略,然后设置http client使用自定义的策略。
主要在于:
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
}
};
}
};
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(
ClientPNames.COOKIE_POLICY, "easy");