自带的CookieStore只能在内存里边管理cookie,但是有的时候需要把cookie保存到文件里边。
为了长久保存cookie,自定义了BasicCookieStore,当添加cookie的时候,都保存到数据库,初始化的时候再从数据里边恢复cookie。
1、自定义的CookieStore
public class CustomCookieStore extends BasicCookieStore {
public CustomCookieStore() {
super();
try {
List<Cookie> cookies = CookieDBManager.getInstance().getAllCookies();
CookieDBManager.getInstance().clear();
Cookie[] cookiesArr = new Cookie[cookies.size()];
for (int i = cookies.size() - 1; i >= 0; i--) {
cookiesArr[i] = cookies.get(i);
}
addCookies(cookiesArr);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized void addCookie(Cookie cookie) {
super.addCookie(cookie);
try {
CookieDBManager.getInstance().saveCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized void addCookies(Cookie[] cookies) {
super.addCookies(cookies);
try {
CookieDBManager.getInstance().saveCookies(cookies);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized void clear() {
super.clear();
try {
CookieDBManager.getInstance().clear();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public synchronized boolean clearExpired(Date date) {
try {
CookieDBManager.getInstance().clearExpired();
} catch (Exception e) {
e.printStackTrace();
}
return super.clearExpired(date);
}
@Override
public synchronized List<Cookie> getCookies() {
return super.getCookies();
}
@Override
public String toString() {
return super.toString();
}
}
2、数据库
public class CookieDBManager {
private final String DB_NAME = "cookie.db";
private final String TABLE_NAME = "cookie";
private DBHelper dbHelper;
private SQLiteDatabase db;
private static CookieDBManager instance;
public static CookieDBManager getInstance() {
if (instance == null) {
instance = new CookieDBManager();
}
return instance;
}
public CookieDBManager() {
dbHelper = new DBHelper(App.getCurrentApp(), DB_NAME, null, 1);
db = dbHelper.getWritableDatabase();
}
private class DBHelper extends SQLiteOpenHelper {
private String SQL_CAREATE_DB = "CREATE TABLE IF NOT EXISTS "//
+ TABLE_NAME + " (" + //
Column.AUTO_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + //
Column.VALUE + " TEXT," + //
Column.NAME + " TEXT," + //
Column.COMMENT + " TEXT," + //
Column.DOMAIN + " TEXT," + //
Column.EXPIRY_DATE + " INTEGER," + //
Column.PATH + " TEXT," + //
Column.SECURE + " INTEGER," + //
Column.VERSION + " TEXT)";//
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CAREATE_DB);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL(SQL_CAREATE_DB);
}
}
public List<Cookie> getAllCookies() {
List<Cookie> cookies = new ArrayList<Cookie>();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(Column.NAME));
String value = cursor
.getString(cursor.getColumnIndex(Column.VALUE));
BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setComment(cursor.getString(cursor
.getColumnIndex(Column.COMMENT)));
cookie.setDomain(cursor.getString(cursor
.getColumnIndex(Column.DOMAIN)));
long expireTime = cursor.getLong(cursor
.getColumnIndex(Column.EXPIRY_DATE));
if (expireTime != 0) {
cookie.setExpiryDate(new Date(expireTime));
}
cookie.setPath(cursor.getString(cursor.getColumnIndex(Column.PATH)));
cookie.setSecure(cursor.getInt(cursor.getColumnIndex(Column.SECURE)) == 1);
cookie.setVersion(cursor.getInt(cursor
.getColumnIndex(Column.VERSION)));
cookies.add(cookie);
}
cursor.close();
return cookies;
}
public void saveCookie(Cookie cookie) {
LogUtil.d("saveCookie:" + cookie);
if (cookie == null) {
return;
}
db.delete(TABLE_NAME, Column.NAME + " = ? ",
new String[] { cookie.getName() });
ContentValues values = new ContentValues();
values.put(Column.VALUE, cookie.getValue());
values.put(Column.NAME, cookie.getName());
values.put(Column.COMMENT, cookie.getComment());
values.put(Column.DOMAIN, cookie.getDomain());
if (cookie.getExpiryDate() != null) {
values.put(Column.EXPIRY_DATE, cookie.getExpiryDate().getDate());
}
values.put(Column.PATH, cookie.getPath());
values.put(Column.SECURE, cookie.isSecure() ? 1 : 0);
values.put(Column.VERSION, cookie.getVersion());
db.insert(TABLE_NAME, null, values);
}
public void saveCookies(Cookie[] cookies) {
LogUtil.d("saveCookies:" + cookies);
if (cookies == null) {
return;
}
db.beginTransaction();
for (Cookie cookie : cookies) {
saveCookie(cookie);
}
db.setTransactionSuccessful();
db.endTransaction();
}
public void clear() {
db.delete(TABLE_NAME, null, null);
}
public void clearExpired() {
long time = System.currentTimeMillis();
db.delete(TABLE_NAME, "EXPIRY_DATE < ? AND EXPIRY_DATE != 0",
new String[] { String.valueOf(time) });
}
private static class Column {
public static final String AUTO_ID = "AUTO_ID";
public static final String VALUE = "VALUE";
public static final String NAME = "NAME";
public static final String COMMENT = "COMMENT";
public static final String DOMAIN = "DOMAIN";
public static final String EXPIRY_DATE = "EXPIRY_DATE";
public static final String PATH = "PATH";
public static final String SECURE = "SECURE";
public static final String VERSION = "VERSION";
}
}
3、把CookieStore设置到httpclient
httpClient.setCookieStore(new CustomCookieStore());