[转帖]android httpclient 管理cookie_Android, Python及开发编程讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Android, Python及开发编程讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3223 | 回复: 0   主题: [转帖]android httpclient 管理cookie        下一篇 
huizai
注册用户
等级:少校
经验:933
发帖:83
精华:0
注册:2013-6-18
状态:离线
发送短消息息给huizai 加好友    发送短消息息给huizai 发消息
发表于: IP:您无权察看 2013-6-26 15:05:23 | [全部帖] [楼主帖] 楼主

自带的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());




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论