We need to use a cookie to read the project today, so I took the opportunity to learn.
1. First the client login succeeds, it gets a cookie that needs to be saved locally and then added to the head after the request.
2. I use Sharepreference to save the key.
/**
* Save Cookies
*/
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 ();//
}
/**
* Get cookies
*/
public static String getpreference (Context context,string key) {
Sharedpreferences preference = context.getsharedpreferences (COOKIE, context.mode_private);
Return preference.getstring (Key, "");
}
/**
* Determine if a cookie exists
*/
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. Obtain a cookie and save it to the database
/**
* Get cookies and save
*/
HttpGet request = new HttpGet (URL);
Esponse = Httpclient.execute (request);
if (Response.getstatusline (). Getstatuscode () = = HTTPSTATUS.SC_OK) {
Get cookies
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 = Cookie.getvalue ();
if (! Textutils.isempty (CookieName)
&&! Textutils.isempty (Cookievalue)) {
Sb.append (cookiename + "=");
Sb.append (cookievalue+ ";");
}
}
Savepreference (Mcontext,sid, sb.tostring ());
}
4. Add to head when requested
HttpGet request = new HttpGet (URL);
if (Gjtcutils.iscookid (Mcontext))
{
Request.addheader ("Cookie", Gjtcutils.getpreference (Mcontext,gjtcconstant.sid));
}
about how Android reads cookies!