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

 

posted @ 2016-04-23 00:24  Catcher8  阅读(3527)  评论(6编辑  收藏  举报