httpclient的cookie处理对我来说总觉得有些复杂,在实现不同的需求时总出现各种各样的莫名其妙问题。
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieSpecFactory csf = new CookieSpecFactory(){
public CookieSpec newInstance(HttpParams params) {
return new BrowserCompatSpec() {
@Override
public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
}
};
}
};
httpclient.getCookieSpecs().register("easy", csf);
httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, "easy");
private static HashMap<String,String> CookieContiner=new HashMap<String,String>() ; /** * 保存Cookie * @param resp */ public void SaveCookies(HttpResponse httpResponse) { Header[] headers = httpResponse.getHeaders("Set-Cookie"); String headerstr=headers.toString(); if (headers == null) return; for(int i=0;i<headers.length;i++) { String cookie=headers[i].getValue(); String[]cookievalues=cookie.split(";"); for(int j=0;j<cookievalues.length;j++) { String[] keyPair=cookievalues[j].split("="); String key=keyPair[0].trim(); String value=keyPair.length>1?keyPair[1].trim():""; CookieContiner.put(key, value); } } } /** * 增加Cookie * @param request */ public void AddCookies(HttpPost request) { StringBuilder sb = new StringBuilder(); Iterator iter = CookieContiner.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); String key = entry.getKey().toString(); String val = entry.getValue().toString(); sb.append(key); sb.append("="); sb.append(val); sb.append(";"); } request.addHeader("cookie", sb.toString()); }