Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Xamarin.Android 應用:讓 HttpClient 與 API 共享 Session

編輯:關於 Android 開發

Xamarin.Android 應用:讓 HttpClient 與 API 共享 Session

前言

進行 Android 開發時,資料通常透過接口取得,這裡的接口泛指 Web API、Web Service、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("https://www.microsoft.com");
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = new CookieContainer();
handler.CookieContainer.Add(uri, new Cookie("name", "value")); // 加入 Cookie
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(uri);
CookieCollection collection = handler.CookieContainer.GetCookies(uri); // 取得 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)); // 加入 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);
}

關鍵在於透過共用的 CookieContainer 保存並帶上 SessionID,讓 App 的多次請求都能被服務端識別為同一個工作階段。若你也在用 Xamarin 開發行動應用,不妨動手試試。對一個概念的認識程度,往往決定了你採取的解決方法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved