博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android如何使用读写cookie的方法
阅读量:5942 次
发布时间:2019-06-19

本文共 4171 字,大约阅读时间需要 13 分钟。

可以使用SharedPreferences或者SQLite来保存用户信息
private static HashMap
  CookieContiner=new HashMap
() ;     /** * 保存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
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却没有太多资料。

先来看一下如何读取cookie吧:

try

        {
          DefaultHttpClient httpclient = new DefaultHttpClient();
          HttpGet httpget = new HttpGet("");
          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 < 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);
     
    }
}

转载于:https://www.cnblogs.com/cosiray/archive/2012/05/09/2491485.html

你可能感兴趣的文章
第十三章:SpringCloud Config Client的配置
查看>>
使用 GPUImage 实现一个简单相机
查看>>
CoinWhiteBook:区块链在慈善事业中的应用
查看>>
Mac上基于Github搭建Hexo博客
查看>>
阿里云服务器ECS开放8080端口
查看>>
前端常用排序详解
查看>>
Spring中实现监听的方法
查看>>
使用Tooltip会出现一个问题,如果行上出现复选框
查看>>
11.03T1 DP
查看>>
P2924 [USACO08DEC]大栅栏Largest Fence
查看>>
jQuery操作table tr td
查看>>
工作总结:MFC自写排序算法(升序)
查看>>
螺旋队列问题之二
查看>>
扩展运算符和解构赋值的理解
查看>>
手机H5显示一像素的细线
查看>>
Menu 菜单栏
查看>>
Integer跟int的区别(备份回忆)
查看>>
集合解析
查看>>
详解分布式应用程序协调服务Zookeeper
查看>>
软件工程之构建之法
查看>>