一、如何获取响应Cookies,例如登录返回的Cookies?
List<String> cookieList = new ArrayList<String>();
if (httpResponse.getHeaders("Set-Cookie") != null) {
Header[] headers = httpResponse.getHeaders("Set-Cookie");
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
cookieList.add(header.getValue());
}
}
二、如何设置请求Cookies?
client.addHeader("Cookie", "需要添加的Cookies");
三、Cookies如何自动管理?
自动管理就是不需要手动获取响应Cookies和添加请求Cookies,框架会自动获取和添加。一般的网络框架都会有方法设置的,例如Async-http-client设置自动管理:
client = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(
paramContext);
client.setCookieStore(myCookieStore);
四、WebView如何设置Cookies?
在调用webView.loadUrl(url)前设置Cookies:
public static void synCookies(Context context, String url) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();//移除
cookieManager.setCookie(url, "需要添加的Cookies");
CookieSyncManager.getInstance().sync();
}
五、Cookies本地保存
Cookies 实际也就是个键值对,所以我们可以直接利用SP字符串形式保存。
public class CookieUtil {
/**
* 保存Cookie
*
* @param context
* @param cookies
*/
public static void setCookies(Context context, List<Cookie> cookies) {
if (cookies != null) {
SharedPreferences sp = context.getSharedPreferences("cookies",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
String loginCookie = "";
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if (cookieName.equals("uid"))
loginCookie = cookieName + "=" + cookieValue;
}
editor.putString("loginCookie", loginCookie);
editor.commit();
}
}
/**
* 读取Cookie
*
* @param context
* @return
*/
public static String getCookies(Context context) {
SharedPreferences sp = context.getSharedPreferences("cookies",
Context.MODE_PRIVATE);
String data = sp.getString("loginCookie", null);
return data;
}
/**
* 清空Cookie
* @param context
*/
public static void removeCookies(Context context){
SharedPreferences sp = context.getSharedPreferences("cookies",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("loginCookie", "");
editor.commit();
}
}
完成了,收工(⊜‿⊜)