Xamarin.Android之封装个简单的网络请求类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Xamarin.Android之封装个简单的网络请求类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含8960字,纯文字阅读大概需要13分钟。
内容图文
一、前言
回忆到上篇 《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 { 23object returnValue = newobject(); 24 HttpClient client = new HttpClient(); 25 client.MaxResponseContentBufferSize = 256000; 26 Uri uri = new Uri(requestUrl); 27var content = new FormUrlEncodedContent(routeParameters); 28try 29 { 30var response = await client.PostAsync(uri, content); 31if (response.IsSuccessStatusCode) 32 { 33var stringValue = await response.Content.ReadAsStringAsync(); 34 returnValue = JsonObject.Parse(stringValue); 35 } 36 } 37catch (Exception ex) 38 { 39throw ex; 40 } 41return 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> 50publicstaticasync Task<object> SendGetRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters) 51 { 52object returnValue = newobject(); 53 HttpClient client = new HttpClient(); 54 client.MaxResponseContentBufferSize = 256000; 55//format the url paramters 56string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value)); 57 Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters)); 58try 59 { 60var response = await client.GetAsync(uri); 61if (response.IsSuccessStatusCode) 62 { 63var stringValue = await response.Content.ReadAsStringAsync(); 64 returnValue = JsonObject.Parse(stringValue); 65 } 66 } 67catch (Exception ex) 68 { 69throw ex; 70 } 71return 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> 81publicstaticasync Task<object> SendGetHttpRequestBaseOnHttpWebRequest(string requestUrl, IDictionary<string, string> routeParameters) 82 { 83object returnValue = newobject(); 84string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value)); 85 Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters)); 86var request = (HttpWebRequest)HttpWebRequest.Create(uri); 87 88using (var response = request.GetResponseAsync().Result as HttpWebResponse) 89 { 90if (response.StatusCode == HttpStatusCode.OK) 91 { 92using (Stream stream = response.GetResponseStream()) 93 { 94using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 95 { 96string stringValue = await reader.ReadToEndAsync(); 97 returnValue = JsonObject.Parse(stringValue); 98 } 99 } 100 } 101 } 102return returnValue; 103 } 104105///<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>111publicstaticasync Task<object> SendPostHttpRequestBaseOnHttpWebRequest(string url, IDictionary<string, string> routeParameters) 112 { 113object returnValue = newobject(); 114115 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); 116 request.Method = "POST"; 117118byte[] postBytes = null; 119 request.ContentType = "application/x-www-form-urlencoded"; 120string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value)); 121 postBytes = Encoding.UTF8.GetBytes(paramters.ToString()); 122123using (Stream outstream = request.GetRequestStreamAsync().Result) 124 { 125 outstream.Write(postBytes, 0, postBytes.Length); 126 } 127128using (HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse) 129 { 130if (response.StatusCode == HttpStatusCode.OK) 131 { 132using (Stream stream = response.GetResponseStream()) 133 { 134using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) 135 { 136string stringValue = await reader.ReadToEndAsync(); 137 returnValue = JsonObject.Parse(stringValue); 138 } 139 } 140 } 141 } 142return returnValue; 143 } 144 } 145 }
需要说明一下的是,我把这个方法当做一个公共方法抽离到一个单独的类库中
三、添加两个数据服务的方法
1 [HttpPost] 2 public ActionResult PostThing(string str) 3 { 4var json = new 5 { 6 Code ="00000", 7 Msg = "OK", 8 Val = str 9 }; 10return Json(json); 11 } 1213public ActionResult GetThing(string str) 14 { 15var json = new16 { 17 Code = "00000", 18 Msg = "OK", 19 Val = str 20 }; 21return 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")] 15publicclass MainActivity : Activity 16 { 17 EditText txtInput; 18 Button btnPost; 19 Button btnGet; 20 Button btnPostHWR; 21 Button btnGetHWR; 22 TextView tv; 2324protectedoverridevoid OnCreate(Bundle bundle) 25 { 26base.OnCreate(bundle); 2728 SetContentView(Resource.Layout.Main); 2930 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); 3637//based on httpclient38 btnPost.Click += PostRequest; 39 btnGet.Click += GetRequest; 40//based on httpwebrequest41 btnPostHWR.Click += PostRequestByHWR; 42 btnGetHWR.Click += GetRequestByHWR; 43 } 4445privateasyncvoid GetRequestByHWR(object sender, EventArgs e) 46 { 47string 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); 50var result = await EasyWebRequest.SendGetHttpRequestBaseOnHttpWebRequest(url, routeParames); 51var data = (JsonObject)result; 52this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest get"; 53 } 5455privateasyncvoid PostRequestByHWR(object sender, EventArgs e) 56 { 57string 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); 60var result = await EasyWebRequest.SendPostHttpRequestBaseOnHttpWebRequest(url, routeParames); 61var data = (JsonObject)result; 62this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest post"; 63 } 6465privateasyncvoid PostRequest(object sender, EventArgs e) 66 { 67string 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); 70var result = await EasyWebRequest.SendPostRequestBasedOnHttpClient(url, routeParames); 71var data = (JsonObject)result; 72this.tv.Text = "hey," + data["Val"] + ", i am from httpclient post"; 73 } 7475privateasyncvoid GetRequest(object sender, EventArgs e) 76 { 77string 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); 80var result = await EasyWebRequest.SendGetRequestBasedOnHttpClient(url, routeParames); 81var data = (JsonObject)result; 82this.tv.Text = "hey," + data["Val"] + ", i am from httpclient get"; 83 } 84 } 85 }
OK,下面看看效果图
如果那位大哥知道有比较好用的开源网络框架推荐请告诉我!!
最后放上本次示例的代码:
https://github.com/hwqdt/Demos/tree/master/src/Catcher.AndroidDemo
原文:http://www.cnblogs.com/catcher1994/p/5423368.html
内容总结
以上是互联网集市为您收集整理的Xamarin.Android之封装个简单的网络请求类全部内容,希望文章能够帮你解决Xamarin.Android之封装个简单的网络请求类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。