導航:首頁 > 操作系統 > Androidgetcookie

Androidgetcookie

發布時間:2022-05-24 17:02:18

① 安卓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之後再與伺服器進行交互。

閱讀全文

與Androidgetcookie相關的資料

熱點內容
三台伺服器配置IP地址 瀏覽:171
如何用命令方塊連續對話 瀏覽:275
win7linux共享文件夾 瀏覽:302
命令符打開本地服務 瀏覽:597
android應用程序源碼 瀏覽:699
安卓開發工程師簡歷怎麼寫 瀏覽:57
熱水器水量伺服器是什麼意思 瀏覽:115
stk衛星編譯 瀏覽:478
對後台程序員的要求 瀏覽:759
ios大文件夾圖標 瀏覽:624
生的計劃pdf 瀏覽:711
oppoa93加密便簽在哪查找 瀏覽:21
兩個數字的加減乘除運算編程 瀏覽:227
給手機加密碼忘記了怎麼辦 瀏覽:601
單片機運算符 瀏覽:297
移動端微信商城源碼 瀏覽:443
編程貓下一個背景在哪裡 瀏覽:359
javaclasstype 瀏覽:240
樂高編程和樂高課的延伸 瀏覽:357
蘋果手機怎麼切換app美國賬號 瀏覽:865