Android如何使用讀寫cookie的方法

Android如何使用讀寫cookie的方法

可使用SharedPreferences或者SQLite來保存用戶信息
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());
    }

作了一個android網絡應用,要求用本身實現的webview去訪問web網站,而且在遠程登陸成功以後把cookie寫入到手機,保留用做之後的自動登陸。找了好多資料。發覺讀取cookies倒還用的很廣泛,但是經過程序寫cookie卻沒有太多資料。html

先來看一下如何讀取cookie吧:android

try
        {
          DefaultHttpClient httpclient = new DefaultHttpClient();
          HttpGet httpget = new HttpGet("http://www.hlovey.com/");
          HttpResponse response = httpclient.execute(httpget);
          HttpEntity entity = response.getEntity();
          List&lt;Cookie&gt; cookies = httpclient.getCookieStore().getCookies();
          if (entity != null) {
              entity.consumeContent();
          }
       
          if (cookies.isEmpty()) {
            Log.i(TAG, "NONE");
         } else {
             for (int i = 0; i &lt; cookies.size(); i++) {            
               Log.i(TAG,"- domain " + cookies.get(i).getDomain());
               Log.i(TAG,"- path " + cookies.get(i).getPath());
               Log.i(TAG,"- value " + cookies.get(i).getValue());
               Log.i(TAG,"- name " + cookies.get(i).getName());
               Log.i(TAG,"- port " + cookies.get(i).getPorts());
               Log.i(TAG,"- comment " + cookies.get(i).getComment());
               Log.i(TAG,"- commenturl" + cookies.get(i).getCommentURL());
               Log.i(TAG,"- all " + cookies.get(i).toString());
             }
         }
          httpclient.getConnectionManager().shutdown();
       
        }catch(Exception e){
          //Todo
        }finally{
        //Todo        
        }
經過分析com.android.browser的源碼,發現android默認的browser增長cookie是在數據庫中增長記錄,和window不一樣,win是採用一個txt文本文件的形式來存儲cookie。而android是將cookie存儲在數據庫中。具體的介紹在《android cookie存儲位置》一文中有介紹。咱們都知道,android每一個應用程序的存儲空間都是獨立的。無論使用preference仍是database存儲,都會在每一個/data/data/package name/下面進行存儲(preference存儲在/data/data/package name/shared_prefs/xxxx.xml)。前面也說到cookie是存在數據庫中,那麼若是採用非瀏覽器訪問網絡須要保留cookie的話咱們就應該在database中創建cookies表,而且存入相應的cookies數據。仿照默認broswer的代碼:web

/**聲明一些數據庫操做的常量*/
  private static SQLiteDatabase mDatabase = null;
  private static final String DATABASE_FILE = "webview.db";
  private static final String COOKIES_NAME_COL = "name";
  private static final String COOKIES_VALUE_COL = "value";
  private static final String COOKIES_DOMAIN_COL = "domain";
  private static final String COOKIES_PATH_COL = "path";
  private static final String COOKIES_EXPIRES_COL = "expires";
  private static final String COOKIES_SECURE_COL = "secure";
mDatabase = LoginApiActivity.this.openOrCreateDatabase(DATABASE_FILE, 0, null);
//建立cookie數據庫
    if (mDatabase != null) {
      // cookies
      mDatabase.execSQL("CREATE TABLE IF NOT EXISTS cookies "
              + " (_id INTEGER PRIMARY KEY, "
              + COOKIES_NAME_COL + " TEXT, " + COOKIES_VALUE_COL
              + " TEXT, " + COOKIES_DOMAIN_COL + " TEXT, "
              + COOKIES_PATH_COL + " TEXT, " + COOKIES_EXPIRES_COL
              + " INTEGER, " + COOKIES_SECURE_COL + " INTEGER" + ");");
      mDatabase.execSQL("CREATE INDEX IF NOT EXISTS cookiesIndex ON "
              + "cookies" + " (path)");
    }
  }
 
/*寫cookie*/
  public void addCookie(Cookie cookie) {
    if (cookie.getDomain() == null || cookie.getPath() == null || cookie.getName() == null
            || mDatabase == null) {
        return;
    }
    String mCookieLock = "asd";
    synchronized (mCookieLock) {
        ContentValues cookieVal = new ContentValues();
        cookieVal.put(COOKIES_DOMAIN_COL, cookie.getDomain());
        cookieVal.put(COOKIES_PATH_COL, cookie.getPath());
        cookieVal.put(COOKIES_NAME_COL, cookie.getName());
        cookieVal.put(COOKIES_VALUE_COL, cookie.getValue());
 
        mDatabase.insert("cookies", null, cookieVal);
     
    }
}數據庫

相關文章
相關標籤/搜索