大叔也說Xamarin~Android篇~為HttpClient共用Session,android與api的session共用機制

來源:互聯網
上載者:User

標籤:

雜談

在進行android進行開發時,我們的資料一般通過介面來獲收,這裡指的介面泛指web api,webservice,wcf,web應用程式等;它們做為服務端與資料庫進行直接通訊,而APP這塊通過向這些介面發Http請求來獲得資料,這樣的好處大叔認為,可以有效降低軟體的開發難度,所以資料互動都被分離到了服務層而,而與客戶互動的功能完全都在APP端,這類似於目前比較流行的SOA架構,即一個服務為多種終端服務;無論是你WEB網站,手機IOS,手機Android,平板還是其它TV之類的,都統一調用服務層的介面!

說的有點遠了,下面來看一下在APP端發送Http時,如何與服務端API進行Session的共用

原理是需要我們清楚的

-〉用戶端

-〉(Request)訪問服務端頁面

-〉服務端產生SessionId

-〉儲存到服務端

-〉(Response)同時向用戶端相應

- 〉用戶端儲存把SessionID到Cookies裡(.net平台cookies裡鍵名為ASP.NET_SessionId)

-〉下次請求,用戶端將在Request頭資訊中把當前SessionID發到服務端

-〉服務端的SessionID通過到期時間維護它的有效性

實踐的代碼來自MSDN

選自:MSDN關於HttpClient的CookieContainer的文章

            Uri uri = new Uri("http://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開發行動裝置 App,就趕快去試試吧!

最後,大叔要說,對一個概念的認識程度決定了你所採取的解決方案!

大叔也說Xamarin~Android篇~為HttpClient共用Session,android與api的session共用機制

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.