关于android如何对cookie的读取!

/** 
* 保存Cookie 
*/  
public static void savePreference(Context context,String key, String value) {  
    SharedPreferences preference = context.getSharedPreferences(COOKIE, Context.MODE_PRIVATE);  
    Editor editor = preference.edit();  
    editor.putString(key, value);  
    editor.commit();//  
}  
/** 
* 得到Cookie 
*/  
public static String getPreference(Context context,String key) {  
    SharedPreferences preference = context.getSharedPreferences(COOKIE, Context.MODE_PRIVATE);  
    return preference.getString(key,"");  
}  
  
/** 
* 判断cookie是否存在 
*/  
public static boolean isCookId(Context context) {  
    SharedPreferences preference = context.getSharedPreferences(GjtcConstant.COOKID, Context.MODE_PRIVATE);  
    Log.d("cook", preference.getString(SID, ""));  
    if (preference.getString(SID, "") != null  
    && !preference.getString(SID, "").equals("")  
    && !preference.getString(SID, "").equals("null")) {  
    return true;  
    } else {  
        return false;  
    }  
}  
3.获得cookie并保存到数据库  
  
/** 
* 获取cookie 并保存 
*/  
  
HttpGet request = new HttpGet(url);  
  
esponse = httpClient.execute(request);  
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
    //获得cookie  
    getCookie(httpClient);  
}  
  
  
private void getCookie(HttpClient httpClient) {  
    List cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();  
    StringBuffer sb = new StringBuffer();  
    for (int i = 0; i < cookies.size(); i++) {  
        Cookie cookie = cookies.get(i);  
        String cookieName = cookie.getName();  
        String cookieValue = cookie.getValue();  
        if (!TextUtils.isEmpty(cookieName) && !TextUtils.isEmpty(cookieValue)) {  
            sb.append(cookieName + "=");  
            sb.append(cookieValue+";");  
        }  
    }  
    savePreference(mContext,SID, sb.toString());  
}  
  
4.请求时添加到head里去  
  
HttpGet request = new HttpGet(url);  
if(GjtcUtils.isCookId(mContext))  
{  
    request.addHeader("cookie", GjtcUtils.getPreference(mContext,GjtcConstant.SID));  
}  

猜你喜欢

转载自blog.csdn.net/qq_32107121/article/details/70242995