Uncle also said Xamarin ~ Android ~ Share Session for HttpClient, session sharing mechanism for android and api, xamarinhttpclient
Miscellaneous
During android development, our data is generally collected through interfaces. The interfaces here refer to web APIs, webservice, wcf, and web applications; they communicate directly with the database as servers, and the APP sends Http requests to these interfaces to obtain data. This benefits uncle believes that it can effectively reduce the difficulty of software development, therefore, data interaction is isolated from the service layer, and the functions of interaction with customers are completely on the APP side. This is similar to the popular SOA architecture, that is, a service serves multiple Terminal Services; whether it's your WEB site, mobile IOS, mobile Android, tablet, or other TV, you can call the service layer interface in a unified way!
This is a bit far away. Let's take a look at how to share the Session with the Server API when the APP sends Http.
The principle is clear to us.
-> Client
-> -〉(Request) Access the server page
-> SessionId generated by the server
-> Store data to the server
-> -〉(Response) At the same time to the client
-> Client stores SessionID in Cookies (ASP. NET_SessionId in cookies of. net platform)
-> In the next Request, the client sends the current SessionID to the server in the Request header.
-> The SessionID of the server maintains its validity through the expiration time.
The practical code comes from MSDN.
From: MSDN CookieContainer article about HttpClient
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 CookieCode in Uncle's Project
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); }
If you are also using xamarin to develop mobile apps, try it now!
Finally, I would like to say that the degree of understanding of a concept determines the solution you have taken!