保存cookie,读取cookie以及判断cookie是否存在
public class Local {
private static SharedPreferences shared;
public static void setShared(SharedPreferences shared) {
Local.shared = shared;
}
public static void saveStrCookie(String cookie) {
SharedPreferences.Editor editor = shared.edit();
editor.putString(Constant.COOKIE_NAME, cookie);
editor.commit();
}
public static boolean hasCookie() {
String _session_id = shared.getString(Constant.COOKIE_NAME, null);
if (_session_id == null || _session_id.equals("")) {
LogUtil.i("hasCookie return false");
return false;
}
LogUtil.i("hasCookie return true");
return true;
}
public static String getCookie() {
String _session_id = shared.getString(Constant.COOKIE_NAME, null);
LogUtil.e("====>getCookie =" + _session_id);
return _session_id;
}
public static void saveCookie(DefaultHttpClient httpClient) {
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
String strCookie = "";
for (Cookie cookie : cookies) {
strCookie = cookie.getValue().toString();
}
LogUtil.e("====>saveCookie = " + strCookie);
saveStrCookie(strCookie);
}
}
将cookie加入CookieStore。
主要就是BasicClientCookie这个类
private void setRequestCookies(DefaultHttpClient client) {
String cookie = Local.getCookie();
Log.i("COOKIE VALUE", cookie);
if (!TextUtils.isEmpty(cookie)) {
BasicClientCookie c = new BasicClientCookie(Constant.COOKIE_NAME,
cookie);
c.setVersion(0);
c.setPath("/");
c.setDomain(Constant.COOKIE_DOMAIN);
client.getCookieStore().addCookie(c);
}
}