Xamarin.Android之封装个简单的网络请求类

一、前言

回忆到上篇 《Xamarin.Android再体验之简单的登录Demo》 做登录时,用的是GET的请求,还用的是同步,

于是现在将其简单的改写,做了个简单的封装,包含基于HttpClient和HttpWebRequest两种方式的封装。

由于对这一块还不是很熟悉,所以可能不是很严谨。

二、先上封装好的代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Json;
  5 using System.Linq;
  6 using System.Net;
  7 using System.Net.Http;
  8 using System.Text;
  9 using System.Threading.Tasks;
 10
 11 namespace Catcher.AndroidDemo.Common
 12 {
 13     public static class EasyWebRequest
 14     {
 15         /// <summary>
 16         /// send the post request based on HttpClient
 17         /// </summary>
 18         /// <param name="requestUrl">the url you post</param>
 19         /// <param name="routeParameters">the parameters you post</param>
 20         /// <returns>return a response object</returns>
 21         public static async Task<object> SendPostRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
 22         {
 23             object returnValue = new object();
 24             HttpClient client = new HttpClient();
 25             client.MaxResponseContentBufferSize = 256000;
 26             Uri uri = new Uri(requestUrl);
 27             var content = new FormUrlEncodedContent(routeParameters);
 28             try
 29             {
 30                 var response = await client.PostAsync(uri, content);
 31                 if (response.IsSuccessStatusCode)
 32                 {
 33                     var stringValue = await response.Content.ReadAsStringAsync();
 34                     returnValue = JsonObject.Parse(stringValue);
 35                 }
 36             }
 37             catch (Exception ex)
 38             {
 39                 throw ex;
 40             }
 41             return returnValue;
 42         }
 43
 44         /// <summary>
 45         /// send the get request based on HttpClient
 46         /// </summary>
 47         /// <param name="requestUrl">the url you post</param>
 48         /// <param name="routeParameters">the parameters you post</param>
 49         /// <returns>return a response object</returns>
 50         public static async Task<object> SendGetRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
 51         {
 52             object returnValue = new object();
 53             HttpClient client = new HttpClient();
 54             client.MaxResponseContentBufferSize = 256000;
 55             //format the url paramters
 56             string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
 57             Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
 58             try
 59             {
 60                 var response = await client.GetAsync(uri);
 61                 if (response.IsSuccessStatusCode)
 62                 {
 63                     var stringValue = await response.Content.ReadAsStringAsync();
 64                     returnValue = JsonObject.Parse(stringValue);
 65                 }
 66             }
 67             catch (Exception ex)
 68             {
 69                 throw ex;
 70             }
 71             return returnValue;
 72         }
 73
 74
 75         /// <summary>
 76         /// send the get request based on HttpWebRequest
 77         /// </summary>
 78         /// <param name="requestUrl">the url you post</param>
 79         /// <param name="routeParameters">the parameters you post</param>
 80         /// <returns>return a response object</returns>
 81         public static async Task<object> SendGetHttpRequestBaseOnHttpWebRequest(string requestUrl, IDictionary<string, string> routeParameters)
 82         {
 83             object returnValue = new object();
 84             string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
 85             Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
 86             var request = (HttpWebRequest)HttpWebRequest.Create(uri);
 87
 88             using (var response = request.GetResponseAsync().Result as HttpWebResponse)
 89             {
 90                 if (response.StatusCode == HttpStatusCode.OK)
 91                 {
 92                     using (Stream stream = response.GetResponseStream())
 93                     {
 94                         using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
 95                         {
 96                             string stringValue = await reader.ReadToEndAsync();
 97                             returnValue = JsonObject.Parse(stringValue);
 98                         }
 99                     }
100                 }
101             }
102             return returnValue;
103         }
104
105         /// <summary>
106         /// send the post request based on httpwebrequest
107         /// </summary>
108         /// <param name="url">the url you post</param>
109         /// <param name="routeParameters">the parameters you post</param>
110         /// <returns>return a response object</returns>
111         public static async Task<object> SendPostHttpRequestBaseOnHttpWebRequest(string url, IDictionary<string, string> routeParameters)
112         {
113             object returnValue = new object();
114
115             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
116             request.Method = "POST";
117
118             byte[] postBytes = null;
119             request.ContentType = "application/x-www-form-urlencoded";
120             string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
121             postBytes = Encoding.UTF8.GetBytes(paramters.ToString());
122
123             using (Stream outstream = request.GetRequestStreamAsync().Result)
124             {
125                 outstream.Write(postBytes, 0, postBytes.Length);
126             }
127
128             using (HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse)
129             {
130                 if (response.StatusCode == HttpStatusCode.OK)
131                 {
132                     using (Stream stream = response.GetResponseStream())
133                     {
134                         using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
135                         {
136                             string stringValue = await reader.ReadToEndAsync();
137                             returnValue = JsonObject.Parse(stringValue);
138                         }
139                     }
140                 }
141             }
142             return returnValue;
143         }
144     }
145 }

需要说明一下的是,我把这个方法当做一个公共方法抽离到一个单独的类库中

三、添加两个数据服务的方法

 1         [HttpPost]
 2         public ActionResult PostThing(string str)
 3         {
 4             var json = new
 5             {
 6                 Code ="00000",
 7                 Msg = "OK",
 8                 Val = str
 9             };
10             return Json(json);
11         }
12
13         public ActionResult GetThing(string str)
14         {
15             var json = new
16             {
17                 Code = "00000",
18                 Msg = "OK",
19                 Val = str
20             };
21             return Json(json,JsonRequestBehavior.AllowGet);
22         }

这两个方法,一个是为了演示post,一个是为了演示get

部署在本地的IIS上便于测试!

四、添加一个Android项目,测试我们的方法

先来看看页面,一个输入框,四个按钮,这四个按钮分别对应一种请求。

然后是具体的Activity代码

 1 using System;
 2 using Android.App;
 3 using Android.Content;
 4 using Android.Runtime;
 5 using Android.Views;
 6 using Android.Widget;
 7 using Android.OS;
 8 using System.Collections.Generic;
 9 using Catcher.AndroidDemo.Common;
10 using System.Json;
11
12 namespace Catcher.AndroidDemo.EasyRequestDemo
13 {
14     [Activity(Label = "简单的网络请求Demo", MainLauncher = true, Icon = "@drawable/icon")]
15     public class MainActivity : Activity
16     {
17         EditText txtInput;
18         Button btnPost;
19         Button btnGet;
20         Button btnPostHWR;
21         Button btnGetHWR;
22         TextView tv;
23
24         protected override void OnCreate(Bundle bundle)
25         {
26             base.OnCreate(bundle);
27
28             SetContentView(Resource.Layout.Main);
29
30             txtInput = FindViewById<EditText>(Resource.Id.txt_input);
31             btnPost = FindViewById<Button>(Resource.Id.btn_post);
32             btnGet = FindViewById<Button>(Resource.Id.btn_get);
33             btnGetHWR = FindViewById<Button>(Resource.Id.btn_getHWR);
34             btnPostHWR = FindViewById<Button>(Resource.Id.btn_postHWR);
35             tv = FindViewById<TextView>(Resource.Id.tv_result);
36
37             //based on httpclient
38             btnPost.Click += PostRequest;
39             btnGet.Click += GetRequest;
40             //based on httpwebrequest
41             btnPostHWR.Click += PostRequestByHWR;
42             btnGetHWR.Click += GetRequestByHWR;
43         }
44
45         private async void GetRequestByHWR(object sender, EventArgs e)
46         {
47             string url = "http://192.168.1.102:8077/User/GetThing";
48             IDictionary<string, string> routeParames = new Dictionary<string, string>();
49             routeParames.Add("str", this.txtInput.Text);
50             var result = await EasyWebRequest.SendGetHttpRequestBaseOnHttpWebRequest(url, routeParames);
51             var data = (JsonObject)result;
52             this.tv.Text = "hey," + data["Val"] + ",  i am from httpwebrequest get";
53         }
54
55         private async void PostRequestByHWR(object sender, EventArgs e)
56         {
57             string url = "http://192.168.1.102:8077/User/PostThing";
58             IDictionary<string, string> routeParames = new Dictionary<string, string>();
59             routeParames.Add("str", this.txtInput.Text);
60             var result = await EasyWebRequest.SendPostHttpRequestBaseOnHttpWebRequest(url, routeParames);
61             var data = (JsonObject)result;
62             this.tv.Text = "hey," + data["Val"] + ",  i am from httpwebrequest post";
63         }
64
65         private async void PostRequest(object sender, EventArgs e)
66         {
67             string url = "http://192.168.1.102:8077/User/PostThing";
68             IDictionary<string, string> routeParames = new Dictionary<string, string>();
69             routeParames.Add("str", this.txtInput.Text);
70             var result = await EasyWebRequest.SendPostRequestBasedOnHttpClient(url, routeParames);
71             var data = (JsonObject)result;
72             this.tv.Text = "hey," + data["Val"] + ",  i am from httpclient post";
73         }
74
75         private async void GetRequest(object sender, EventArgs e)
76         {
77             string url = "http://192.168.1.102:8077/User/GetThing";
78             IDictionary<string, string> routeParames = new Dictionary<string, string>();
79             routeParames.Add("str", this.txtInput.Text);
80             var result = await EasyWebRequest.SendGetRequestBasedOnHttpClient(url, routeParames);
81             var data = (JsonObject)result;
82             this.tv.Text = "hey," + data["Val"] + ",  i am from httpclient get";
83         }
84     }
85 }

OK,下面看看效果图

      

如果那位大哥知道有比较好用的开源网络框架推荐请告诉我!!

最后放上本次示例的代码:

https://github.com/hwqdt/Demos/tree/master/src/Catcher.AndroidDemo

时间: 2024-10-06 00:30:41

Xamarin.Android之封装个简单的网络请求类的相关文章

Swift2.0:使用协议(Protocols)和闭包(Closures)封装一个简单的网络请求类

一,使用闭包封装 一, 验证 二,使用代理

Android之封装好的异步网络请求框架

1.简介 Android中网络请求一般使用Apache HTTP Client或者采用HttpURLConnection,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用这个MyHttpUtils库可以大大的简化操作,它是基于HttpURLConnection,所有的请求都是独立在UI主线程之外,没有通过CommCallback回调方法处理请求结果, 没有了子线程.没有了handle,链式的变成使得代码更加清晰 . 2.特性 支持get.post请求,文件下载,上传

基于Volley,Gson封装支持JWT无状态安全验证和数据防篡改的GsonRequest网络请求类

这段时间做新的Android项目的客户端和和REST API通讯框架架构设计,使用了很多新技术,最终的方案也相当简洁优雅,客户端只需要传Java对象,服务器端返回json字符串,自动解析成Java对象, 无状态安全验证基于JWT实现,JWT规范的细节可以参考我前面的文章.JWT的token和数据防篡改签名统一放在HTTP Header中,这样就实现了对请求内容和返回结果的无侵入性,服务器端也可以在全局过滤器中统一处理安全验证. Android客户端使用了Volley网络请求框架和Gson解析库,

ios中封装网络请求类

ios中封装网络请求类 #import "JSNetWork.h" //asiHttpRequest #import "ASIFormDataRequest.h" //xml 的解析 #import "UseXmlParser.h" //判断是否联网 #import "Reachability.h" //sbJson,判断json的解析 #import "JSON.h" @implementation JS

block传值以及利用block封装一个网络请求类

1.block在俩个UIViewController间传值 最近刚学了几招block 的高级用法,其实就是利用block语法在俩个UIViewController之间传值,在这里分享给初学者,同时也方便我自己理解.我们知道UINavigationController类管理UIViewController的时候,利用的是"栈"的思想,在这里不做过多解释,切入正题,假设我们现在有俩个UIViewController,viewC1和viewC2,viewC1比viewC2先进入到UINavi

Xamarin.Android再体验之简单的登录Demo

一.前言 在空闲之余,学学新东西 二.服务端的代码编写与部署 这里采取的方式是MVC+EF返回Json数据,(本来是想用Nancy来实现的,想想电脑太卡就不开多个虚拟机了,用用IIS部署也好) 主要是接受客户端的登陆请求,服务器端返回请求的结果 这里的内容比较简单不在啰嗦,直接上代码了: 1 using System.Linq; 2 using System.Web.Mvc; 3 namespace Catcher.AndroidDemo.EasyLogOn.Service.Controller

android 项目中使用到的网络请求框架以及如何配置好接口URL

我们在做项目中一定少不了网络请求,现在很多公司的网络请求这块好多都是使用一些比较好的开源框架,我项目中使用的是volley,现在讲讲一些volley基本的使用,如果想要详细的了解就要去看它的源码了,现在贴代码讲一些它的使用了, 首先用一个类去封装下它的基本配置信息,以后需要变动的话,就直接在这里做修改,android最好能把每个功能都独立出来,这样做修改的话 不会导致出现其他的bug,特别在有新员工进入到项目组中,分配任务沟通起来也省事, ProtocolManager.java  它是一个单例

Xamarin.Android之Spinner的简单探讨

一.前言 今天用了一下Spinner这个控件,主要是结合官网的例子来用的,不过官网的是把数据写在Strings.xml中的, 某种程度上,不是很符合我们需要的,比较多的应该都是从数据库读出来,绑定上去的.下面是官网的例子: https://developer.xamarin.com/guides/android/user_interface/spinner/ 二.来个简单的Demo 新建一个类 MyType.cs 1 public class MyType 2 { 3 public int Ty

用c#开发安卓程序 (xamarin.android)系列之二 简单的聊天程序

networkcomm.net 网络通信框架来自于英国剑桥,其开源版本2.3.1 中自带了一个编写android的例子,可以很好的帮助我们入门. 此示例的功能,是在2个安卓手机上,输入对方的IP和端口,能够实现聊天功能. 把代码放上,供大家一览 using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using