android端和服務端session保持
阿新 • • 發佈:2019-02-05
為了保持服務端的session,我首先想到的辦法就是沒隔一段時間呼叫一下我們的伺服器。
之前出了總總問題,什麼timeoutException,ClientProtocolException等等問題,我講慢慢解釋.
我在service中做輪詢呼叫伺服器保持session時,只要出現一次timeoutexception,接著就會出現ClientProtocolException,後來發現這是重定向導致的問題,然後在AsyncHttpClient中設定了
但是這麼一設定又會出一個問題,我在登入的時候總是報302,又回到了重定向的問題。client.setEnableRedirects(false); client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, false);
我發現服務端在給我設定attribute傳遞cookies的時候,使用了重定向。沒辦法,只能將setEnableRedirects再次開啟。
還有一個問題就是在AsyncHttpClient話說是自動儲存CookieStore的,但是我列印了log,結果CookieStore是為null,導致我在做輪詢的時候,是沒有向服務端提交Cookie的,這樣過了30分鐘服務端的session任然會超時。
於是手動的加上
CookieStore cookieStore = new PersistentCookieStore(this); cline.setCookieStore(cookieStore);
然後列印log
發現這次才有值。CookieStore cookieStore = new PersistentCookieStore(this); cline.setCookieStore(cookieStore); HttpContext httpContext = cline.getHttpContext(); CookieStore cookies = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE); if(cookies!=null){ for(Cookie c:cookies.getCookies()){ LogUtil.d("login activtity onsuccess before ~~"+c.getName(),c.getValue()); } }else{ LogUtil.d("login activtity onsuccess before~~","cookies is null"); }
哈哈,明白了吧,你需要在登入的時候手動新增
CookieStore cookieStore = new PersistentCookieStore(this);
cline.setCookieStore(cookieStore);
才可以的。