① 安卓cookie,cookie是什么cookie是什么
COOKIE是指你上网时候输入的私密和访问过的网络的一个小,直接翻译是甜饼。他一般在C盘主要是为了方便下次再访问这些网页.如果上网的防病措施...
android如何使用读写cookie的方法
可以使用SharedPreferences或者SQLite来保存用户信息
private static HashMap<String,String> CookieContiner=new HashMap<String,String>() ;
/**
* 保存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<headers.length;i++)
{
String cookie=headers[i].getValue();
String[]cookievalues=cookie.split(";");
for(int j=0;j<cookievalues.length;j++)
{
String[] keyPair=cookievalues[j].split("=");
String key=keyPair[0].trim();
String value=keyPair.length>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("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 < 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);
}
}
② android 用httpclient登录无法保持会话状态 最后两次请求的cookie都不一样!我明明设成一样了
loginResult = EntityUtils.toString(loginResponse.getEntity(), "utf-8");
得判断是否真成功了。 另外服务器送来的cookie是否一样,那要看服务器送什么回来。现在这样单方面调试,很费劲的
③ 安卓Android开发,afinal中的FinalHttp如何获取和设置cookie
1.获取
finalHttp = new FinalHttp();
finalHttp.post(API.server, ajaxParams, new AjaxCallBack<String>() {
@Override public void onFailure(Throwable t, int errorNo, String strMsg) { super.onFailure(t, errorNo, strMsg);
closeProgressDialog();
prompt(getResources().getString(R.string.request_time_out));
System.out.println("errorNo:" + errorNo + ",strMsg:" + strMsg);
}
@Override public void onStart() { super.onStart();
showProgressDialog(getResources().getString(R.string.loading));
}
@Override public void onLoading(long count, long current) { super.onLoading(count, current);
}
@Override public void onSuccess(String t) { super.onSuccess(t); //从服务器获取CookieStore,保存到MyCookieStore
DefaultHttpClient client=(DefaultHttpClient)finalHttp.getHttpClient();
MyCookieStore.cookieStore = client.getCookieStore(); if (!StringUtils.isBlank(t)) {
Log.e(TAG, Constant.RESULT + API.GET_VERIFY_CODE + "
" + t.toString());
JSONStatus jsonStatus = BaseJSONData(t); if (jsonStatus.isSuccess) {
handler.sendMessage(handler.obtainMessage(GET_VERIFY_CODE_SUCCESS, BaseJSONData(t)));
} else {
handler.sendMessage(handler.obtainMessage(GET_VERIFY_CODE_FALSE, BaseJSONData(t)));
}
} else {
prompt(getResources().getString(R.string.request_no_data));
}
}
});
2.设置
OverridepublicvoidinitData() {finalHttp =newFinalHttp();//配置已保存的CookieStore,保证处于同一session中请求finalHttp.configCookieStore(MyCookieStore.cookieStore);finalHttp.post(API.server, ajaxParams,newAjaxCallBack<String>() {......(省略)}}
格式不行,凑合看吧
点赞+关注谢谢
④ Android开发中怎样使用cookieManager来管理cookie
1、首先 在android应用程序开始的activity中的oncreaty()方法中注册cookiemanager。如下:
<span style="font-size:18px;">//设置网络请求cookie
CookieSyncManager.createInstance(this);</span>
2、然后在到网络请求的那个类中设置如下 设置和获取cookie的方法
<span style="font-size:18px;"> protected String getCookie() {
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie("cookie");
if (cookie != null) {
return cookie;
} else {
return "";
}
}
protected void setCookie(String cookie) {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie("cookie", cookie);
}</span>
3、最后一步就在urlConnection.openConnectin()的后面设置如下方法:
uc = (HttpURLConnection) new URL(url + "?" + paramsStr.toString()).openConnection();
uc.setRequestProperty("Cookie", getCookie());
<pre style="background-color:#2b2b2b;color:#a9b7c6;font-family:'宋体';font-size:12.0pt;"><span style="background-color:#344134;">setCookies</span>(uc.getHeaderFields())<span style="color:#cc7832;">;</span>
好了到这里就完成了cookie的设置
3. 过期按需处理一下
附1:cookie的获取
response.headerFields = conn.getHeaderFields();
setCookies(response.headerFields);
/**
* 存储cookie
* @param headerFields
*/
protected void setCookies(Map<String, List<String>> headerFields) {
if (null == headerFields) {
return;
}
List<String> cookies = headerFields.get(COOKIES_KEY);
if (null == cookies) {
return;
}
for (String cookie : cookies) {
setCookie(cookie);
}
}
⑤ android retrofit cookie怎么处理
首先是抽象的基类
public abstract class BaseApi {
public static final String API_SERVER = "服务器地址"
private static final OkHttpClient mOkHttpClient = new OkHttpClient();
private static Retrofit mRetrofit;
protected static Retrofit getRetrofit() {
if (Retrofit == null) {
Context context = Application.getInstance().getApplicationContext();
//设定30秒超时
mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
//设置拦截器,以用于自定义Cookies的设置
mOkHttpClient.networkInterceptors()
.add(new CookiesInterceptor(context));
//设置缓存目录
File cacheDirectory = new File(context.getCacheDir()
.getAbsolutePath(), "HttpCache");
Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
mOkHttpClient.setCache(cache);
//构建Retrofit
mRetrofit = new Retrofit.Builder()
//配置服务器路径
.baseUrl(API_SERVER + "/")
//设置日期解析格式,这样可以直接解析Date类型
.setDateFormat("yyyy-MM-dd HH:mm:ss")
//配置转化库,默认是Gson
.addConverterFactory(ResponseConverterFactory.create())
//配置回调库,采用Rxjava
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
//设置OKHttpClient为网络客户端
.client(mOkHttpClient)
.build();
}
return mRetrofit;
}
}
然后是Cookies拦截器
public class CookiesInterceptor implements Interceptor{
private Context context;
public CookiesInterceptor(Context context) {
this.context = context;
}
//重写拦截方法,处理自定义的Cookies信息
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request compressedRequest = request.newBuilder()
.header("cookie", CookieUtil.getCookies(context))
.build();
Response response = chain.proceed(compressedRequest);
CookieUtil.saveCookies(response.headers(), context);
return response;
}
}123456789101112131415161718
CookieUtil则是一些自定义解析和生成方法以及SharedPreferences的存取,代码略
然后是Api类
public class UserApi extends BaseApi{
//定义接口
private interface UserService {
//GET注解不可用@FormUrlEncoded,要用@Query注解引入请求参数
@GET("user/user_queryProfile")
Observable<UserProfileResp> queryProfile(@Query("userId") int userId);
//POST方法没有缓存,适用于更新数据
@FormUrlEncoded
@POST("user/user_updateUserName")
Observable<BaseResp> updateUserName(@Field("userName") String userName);
}
protected static final UserService service = getRetrofit().create(UserService.class);
//查询用户信息接口
public static Observable<UserProfileResp> queryProfile(int userId){
return service.queryProfile(userId);
}
//更新用户名接口
public static Observable<BaseResp> updateUserName(String userName){
return service.updateUserName(userName);
}
}
再就是将Retrofit的响应消息经过Gson解析成期望的数据结构,称之为Model类
上文的BaseResp和UserProfileResp则是自定义的Model
假定服务器约定返回的Json格式为
{
"result":"结果代号,0表示成功",
"msg":"异常信息,仅在失败时返回数据",
"userInfo":
{
"id":"用户id",
"userName":"用户名名字"
}
}123456789
那么UserProfileResp可以写成
public class UserProfileResp {
//@SerializedName是指定Json格式中的Key名
//可以不写,则默认采用与变量名一样的Key名
@SerializedName("userInfo")
private UserProfileModel userInfo;
public UserProfileModel getUserInfo() {
return userInfo;
}
}12345678910
UserProfileModel则是具体的数据结构
public class UserProfileModel {
private int userId;
private String userName;
public String getUserName(){
return userName;
}
}12345678
需要注意的是,如果没有使用@SerializedName指定Key名,当工程被混淆时,变量名会被混淆得与期望的Key名不符。因此需要将这类Model类统一放到一个工程目录,再在proguard-project文件中加入排除项
//不混淆Model类
-keep class com.xxx.model.xxx.** { *; }12
最后是实际调用
public void getProfile(int userId){
UserApi.queryProfile(userId)
.subscribeOn(Schelers.io())
.subscribe(new Subscriber<UserProfileResp>(){
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(UserProfileResp userProfileResp) {
}
});
}
⑥ android webview 如何存储cookie
在App中嵌入网页,使用Nativie方式登录,然后将cookie保存到WebView中,实现免登录功能。同步Cookie到WebView的方法可以参考下面的代码:
/**
* Sync Cookie
*/
private void syncCookie(Context context, String url){
try{
Log.d("Nat: webView.syncCookie.url", url);
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();// 移除
cookieManager.removeAllCookie();
String oldCookie = cookieManager.getCookie(url);
if(oldCookie != null){
Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
}
StringBuilder sbCookie = new StringBuilder();
sbCookie.append(String.format("JSESSIONID=%s","INPUT YOUR JSESSIONID STRING"));
sbCookie.append(String.format(";domain=%s", "INPUT YOUR DOMAIN STRING"));
sbCookie.append(String.format(";path=%s","INPUT YOUR PATH STRING"));
String cookieValue = sbCookie.toString();
cookieManager.setCookie(url, cookieValue);
CookieSyncManager.getInstance().sync();
String newCookie = cookieManager.getCookie(url);
if(newCookie != null){
Log.d("Nat: webView.syncCookie.newCookie", newCookie);
}
}catch(Exception e){
Log.e("Nat: webView.syncCookie failed", e.toString());
}
}
使用上面的方法可以将Cookie同步到WebView中,这样浏览网页时即可实现免登录。
但是在实际使用过程中会出现Cookie并未保存成功,每次都会跳转到登录页面应为初始化WebView时漏掉了重要的东西。可以参考下面代码设置WebView。
/**
* init WebView Settings
* */
private void initWebViewSettings(){
// myWebView.getSettings().setSupportZoom(true);
// myWebView.getSettings().setBuiltInZoomControls(true);
// myWebView.getSettings().setDefaultFontSize(12);
// myWebView.getSettings().setLoadWithOverviewMode(true);
// 设置可以访问文件
myWebView.getSettings().setAllowFileAccess(true);
//如果访问的页面中有Javascript,则webview必须设置支持Javascript
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setUserAgentString(MyApplication.getUserAgent());
myWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setDatabaseEnabled(true);
}
完成以上两步操作,再次运行程序,就会发现,打开网页后不会再跳转到登录页面了。
⑦ 怎样解决Android获取服务器中的session问题啊
CookieManager
cm
=
CookieManager.getInstance();
cm.removeAllCookie();
cm.getCookie(url);
cm.setCookie(url,
cookie);另外还有个CookieSyncManager,没搞清干嘛使的,但是我按以下顺序调用,设置Cookie没问题CookieSyncManager
csm
=
CookieSyncManager.createInstance(this);CookieManager
cm
=
CookieManager.getInstance();cm.removeAllCookie();csm.sync();cm.setCookie(url,
cookie);
⑧ 为什么.net开发的webapp在android机上不能鎐ookie
Android中在使用OkHttp这个库的时候,有时候需要持久化Cookie,那么怎么实现呢。OkHttp的内部源码过于复杂,不进行深究,这里只看其中的HttpEngineer里面的部分源码,在发起请求以及请求结束都会调用这个类的几个方法。我们先看networkRequest方法,在里面通过client.getCookieHandler()函数获得了CookieHandler对象,通过该对象拿到cookie并设置到请求头里,请求结束后取得响应后通过networkResponse.headers()函数将请求头获得传入receiveHeaders函数,并将取得的cookie存入getCookieHandler得到的一个CookieHandler对象中去
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
This client doesn't specify a default {@code Accept} header because it
* doesn't know what content types the application is interested in.
*/
private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();
//此处省略n行代码......
CookieHandler cookieHandler = client.getCookieHandler();
if (cookieHandler != null) {
// Capture the request headers added so far so that they can be offered to the CookieHandler.
// This is mostly to stay close to the RI; it is unlikely any of the headers above would
// affect cookie choice besides Host.
Map<string, string="">> headers = OkHeaders.toMultimap(result.build().headers(), null);
Map<string, string="">> cookies = cookieHandler.get(request.uri(), headers);
// Add any new cookies to the request.
OkHeaders.addCookies(result, cookies);
}
//此处省略n行代码......
return result.build();
} data-snippet-id=ext. data-snippet-saved=false data-csrftoken=bFkHGE1O-cy7WY9D6w70F6qK9YUKZHLynI5g data-codota-status=done><code class="hljs" java="">/**
* Populates request with defaults and cookies.
*
* </code><p><code class="hljs" java="">This client doesn't specify a default {@code Accept} header because it
* doesn't know what content types the application is interested in.
*/
private Request networkRequest(Request request) throws IOException {
Request.Builder result = request.newBuilder();
//此处省略n行代码......
CookieHandler cookieHandler = client.getCookieHandler();
if (cookieHandler != null) {
// Capture the request headers added so far so that they can be offered to the CookieHandler.
// This is mostly to stay close to the RI; it is unlikely any of the headers above would
// affect cookie choice besides Host.
Map<string, string="">> headers = OkHeaders.toMultimap(result.build().headers(), null);
Map<string, string="">> cookies = cookieHandler.get(request.uri(), headers);
// Add any new cookies to the request.
OkHeaders.addCookies(result, cookies);
}
//此处省略n行代码......
return result.build();
}</string,></string,></code></p></string,></string,>
?
1
2
3
4
5
6
7
<code class="hljs" java="">public void readResponse() throws IOException {
//此处省略n行代码......
receiveHeaders(networkResponse.headers());
//此处省略n行代码......
}</code>
?
1
2
3
4
5
6
<code class="hljs" java="">public void receiveHeaders(Headers headers) throws IOException {
CookieHandler cookieHandler = client.getCookieHandler();
if (cookieHandler != null) {
cookieHandler.put(userRequest.uri(), OkHeaders.toMultimap(headers, null));
}
}</code>
而这个CookieHandler对象是OkHttpClient类中的一个属性,提供了getter和setter方法,默认的构造函数OkHttpClient client = new OkHttpClient();不会创建这个CookieHandler对象。假设我们传入了这个对象,那么OkHttp自然会进行cookie的自动管理了。
?
1
2
3
4
5
6
7
8
9
<code class="hljs" cs="">private CookieHandler cookieHandler;
public OkHttpClient setCookieHandler(CookieHandler cookieHandler) {
this.cookieHandler = cookieHandler;
return this;
}
public CookieHandler getCookieHandler() {
return cookieHandler;
}</code>
那么假设我们将CookieHandler对象传入
?
1
2
<code axapta="" class="hljs">OkHttpClient client = new OkHttpClient();
client.setCookieHandler(CookieHandler cookieHanlder);</code>
那么,现在关键是如何去实现这个CookieHandler 对象。CookieManager是CookieHandler 的一个子类,其构造函数 public CookieManager(CookieStore store, CookiePolicy cookiePolicy)需要传入两个参数,CookieStore 是一个接口,因此我们实现CookieStore接口中的抽象方法,即可实现这个CookieHandler 对象。参考android-async-http这个库,它具有cookie的自动管理功能,主要我们参考其中的两个类
PersistentCookieStore SerializableCookie
参考以上两个类并做适当修改,得到了如下两个类,他们的功能就是将cookie保持在SharedPreferences中。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<code avrasm="" class="hljs">package com.kltz88.okhttp.cookie;
/**
* User:lizhangqu([email protected])
* Date:2015-07-13
* Time: 17:31
*/
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.HttpCookie;
public class SerializableHttpCookie implements Serializable {
private static final long serialVersionUID = 6374381323722046732L;
private transient final HttpCookie cookie;
private transient HttpCookie clientCookie;
public SerializableHttpCookie(HttpCookie cookie) {
this.cookie = cookie;
}
public HttpCookie getCookie() {
HttpCookie bestCookie = cookie;
if (clientCookie != null) {
bestCookie = clientCookie;
}
return bestCookie;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getCommentURL());
out.writeObject(cookie.getDomain());
out.writeLong(cookie.getMaxAge());
out.writeObject(cookie.getPath());
out.writeObject(cookie.getPortlist());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.getSecure());
out.writeBoolean(cookie.getDiscard());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
}
}</code>
?
⑨ android webview加载页面怎么得到cookies值
我们可以在 WebViewClient 的 onPageFinished(WebView view, String url) 方法中使用 CookieManager 来获取加载完成之后网页中携带的 Cookie 值,代码如下: private class MyWebViewClient extends WebViewClient { public boolean shouldOverrideUrlLoading(WebView view, String url) { webview.loadUrl(url); return true; } public void onPageFinished(WebView view, String url) { CookieManager cookieManager = CookieManager.getInstance(); String CookieStr = cookieManager.getCookie(url); Log.e("sunzn", "Cookies = " + CookieStr); super.onPageFinished(view, url); } }
⑩ android 怎么判断cookie有没有到期
Cookie实际上是一小段文本信息。在Web程序中,客户端浏览器请求服务器,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie。客户端浏览器会把Cookie保存起来。当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie一同提交给服务器。服务器检查该Cookie,以此来辨认用户状态。服务器还可以根据需要修改Cookie的内容。
Cookie的失效时间由maxAge属性决定,单位为秒(Second)。Cookie中通过getMaxAge()方法与setMaxAge(int maxAge)方法来读写maxAge属性。从客户端读取Cookie时,包括maxAge在内的其他属性都是不可读的,也不会提交。浏览器提交Cookie时只会提交name与value属性。maxAge属性只被浏览器用来判断Cookie是否过期。
对于android客户端,登录成功后服务器会向客户端颁发一个Cookie,客户端将Cookie持久化到本地。当客户端再次请求该服务器时,客户端会把请求的网址连同该Cookie一同提交给服务器。服务器检查该Cookie,以此来辨认用户状态。对于Cookie的有效期,是在客户端本地判断的,Cookie有效则可以向服务器进行请求;Cookie失效则需重新登录获取新的Cookie之后再与服务器进行交互。