大叔也说Xamarin~Android篇~为HttpClient共享Session,android与api的session共享机制
2016-01-12 22:23
435 查看
回到目录
说的有点远了,下面来看一下在APP端发送Http时,如何与服务端API进行Session的共享
-〉(Request)访问服务端页面
-〉服务端产生SessionId
-〉存储到服务端
-〉(Response)同时向客户端相应
- 〉客户端存储把SessionID到Cookies里(.net平台cookies里键名为ASP.NET_SessionId)
-〉下次请求,客户端将在Request头信息中把当前SessionID发到服务端
-〉服务端的SessionID通过过期时间维护它的有效性
大家如果也在使用xamarin开发移动应用,就赶快去试试吧!
最后,大叔要说,对一个概念的认识程度决定了你所采取的解决方法!
回到目录
杂谈
在进行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开发移动应用,就赶快去试试吧!
最后,大叔要说,对一个概念的认识程度决定了你所采取的解决方法!
回到目录
相关文章推荐
- 使用URLConnection进行http请求
- IP/TCP 端口
- Android网络请求
- 高性能Socket组件和RPC,让你像写本地代码一样开发网络应用和分布式程序
- 网络编程五阶段总结
- Xcode7HTTP请求以及真机调试
- 网络编程四阶段总结
- Android中Okhttp和SPDY协议
- httpd(2.2&2.4)RPM搭建配置定义详解
- Linux 系统应用编程——网络编程(基础篇)
- 计算机网络复习
- [机器学习] Coursera ML笔记 - 神经网络(Learning)
- 从僵尸网络追踪到入侵检测 第8章 Honeyd配置文件使用
- Android网络请求心路历程
- 【转】TCP/IP报文格式
- CentOS 7安装配置Apache HTTP Server
- Xcode7 网络请求报错:The resource could not be loaded because the App Transport Security policy requir
- XMLHttpRequest对象的status属性状态吗
- 【主席树】BZOJ 1146 network网络管理
- 用caffe训练人工神经网络