首页 > 代码库 > 关于android如何对cookie的读取!
关于android如何对cookie的读取!
今天做项目时需要用到cookie读取,于是就乘机学习了下。
1.首先客户端登录成功后会得到一个cookie ,需要把这个cookie保存到本地,然后后面需要请求时加到head。
2.我用的是sharePreference保存key的。
/**
* 保存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<Cookie> 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 = http://www.mamicode.com/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));
}
关于android如何对cookie的读取!