android讀寫cookie的方法

來源:互聯網
上載者:User

做了一個android網路應用,要求用自己實現的webview去訪問web網站,並且在遠程登入成功之後把cookie寫入到手機,保留用作以後的自動登入。找了好多資料。發覺讀取cookies倒還用的很普遍,可是通過程式寫cookie卻沒有太多資料。

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

try
        {
          DefaultHttpClient httpclient = new DefaultHttpClient();
          HttpGet httpget = new HttpGet("http://www.hlovey.com");
          HttpResponse response = httpclient.execute(httpget);
          HttpEntity entity = response.getEntity();
          List<Cookie> 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的代碼:

/**聲明一些資料庫操作的常量*/
  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);
      
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.