大(da)叔(shu)也說Xamarin~Android篇~為HttpClient共(gong)享Session,android與(yu)api的session共(gong)享機制
雜談
在進行android進行開(kai)發時,我們(men)的(de)(de)數(shu)據(ju)(ju)一般通(tong)過(guo)接(jie)口(kou)來(lai)獲(huo)收,這(zhe)里指的(de)(de)接(jie)口(kou)泛指web api,webservice,wcf,web應用程(cheng)序等(deng);它們(men)做為服(fu)(fu)務(wu)端(duan)(duan)與(yu)數(shu)據(ju)(ju)庫進行直接(jie)通(tong)訊(xun),而(er)APP這(zhe)塊通(tong)過(guo)向這(zhe)些接(jie)口(kou)發Http請求來(lai)獲(huo)得數(shu)據(ju)(ju),這(zhe)樣(yang)的(de)(de)好處大叔認(ren)為,可以有效的(de)(de)降低軟件的(de)(de)開(kai)發難(nan)度,所以數(shu)據(ju)(ju)交互(hu)都被分(fen)離到(dao)了服(fu)(fu)務(wu)層而(er),而(er)與(yu)客戶交互(hu)的(de)(de)功能完全都在APP端(duan)(duan),這(zhe)類(lei)似于(yu)目前比較(jiao)流(liu)行的(de)(de)SOA架構,即一個服(fu)(fu)務(wu)為多種(zhong)終(zhong)端(duan)(duan)服(fu)(fu)務(wu);無論是你(ni)WEB網站,手(shou)機IOS,手(shou)機Android,平板還是其它TV之類(lei)的(de)(de),都統(tong)一調用服(fu)(fu)務(wu)層的(de)(de)接(jie)口(kou)!
說的(de)有點遠了,下面來看一下在APP端(duan)發送Http時(shi),如何與服(fu)務(wu)端(duan)API進行Session的(de)共享
原理是需要我們清楚的
-〉客戶端
-〉(Request)訪問服務端頁面
-〉服(fu)務(wu)端產生SessionId
-〉存儲到服務端
-〉(Response)同時向客戶端相應
- 〉客戶端存儲把SessionID到Cookies里(li)(.net平臺cookies里(li)鍵名(ming)為ASP.NET_SessionId)
-〉下(xia)次請求,客(ke)戶(hu)端將在Request頭(tou)信(xin)息(xi)中把當(dang)前(qian)SessionID發到服務端
-〉服務端的SessionID通(tong)過過期時間維護它(ta)的有效性
實踐的代碼來自MSDN
選自:
Uri uri = new Uri("//www.microsoft.com"); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = new CookieContainer(); handler.CookieContainer.Add(uri, new Cookie("name", "value")); // Adding a Cookie HttpClient client = new HttpClient(handler); HttpResponseMessage response = await client.GetAsync(uri); CookieCollection collection = handler.CookieContainer.GetCookies(uri); // Retrieving a Cookie
大叔項目里的代碼
Uri uri = new Uri(GetString(Resource.String.apiHost)); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = new CookieContainer(); handler.CookieContainer.Add(uri, new Cookie("ASP.NET_SessionId", InMemory.SessionID)); // Adding a Cookie using (var http = new HttpClient(handler)) { var content = new FormUrlEncodedContent(new Dictionary<string, string>() { }); var response = http.PostAsync(GetString(Resource.String.apiHost) + "/Test/CurrentTaskListApi", content); var obj = JsonConvert.DeserializeObject<List<Task_Info>>(response.Result.Content.ReadAsStringAsync().Result); listView.Adapter = new Task_InfoListAdapter(this, obj); }
大家如果也在使用xamarin開發移動應用,就(jiu)趕快去試試吧!
最后,大叔(shu)要說,對一個概念(nian)的(de)認識程度決定(ding)了你所采取的(de)解決方法!