• 大叔也说Xamarin~Android篇~为HttpClient共享Session,android与api的session共享机制


    回到目录

    杂谈

    在进行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开发移动应用,就赶快去试试吧!

    最后,大叔要说,对一个概念的认识程度决定了你所采取的解决方法!

    回到目录

  • 相关阅读:
    docker创建nginx+php-fpm+mysql环境(一分钟搭建lnmp)
    dcoker搭建wordpress
    docker搭建mysql
    nginx负载均衡精简配置实例
    docker配置阿里云镜像加速
    Centos7 ssh配置RSA证书登录
    Dockerfile centos7_php5.6.36
    Dockerfile cnetos7_nginx1.15.10
    Dockerfile centos7_tomcat7.0.64_jdk7u80
    centos7 安装docker
  • 原文地址:https://www.cnblogs.com/lori/p/5125817.html
Copyright © 2020-2023  润新知