回憶到上篇 《Xamarin.Android再體驗之簡單的登陸Demo》 作登陸時,用的是GET的請求,還用的是同步,html
因而如今將其簡單的改寫,作了個簡單的封裝,包含基於HttpClient和HttpWebRequest兩種方式的封裝。git
因爲對這一塊還不是很熟悉,因此可能不是很嚴謹。github
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 }
須要說明一下的是,我把這個方法當作一個公共方法抽離到一個單獨的類庫中web
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,一個是爲了演示getjson
部署在本地的IIS上便於測試!網絡
先來看看頁面,一個輸入框,四個按鈕,這四個按鈕分別對應一種請求。app
而後是具體的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,下面看看效果圖async
若是那位大哥知道有比較好用的開源網絡框架推薦請告訴我!!ide
最後放上本次示例的代碼:
https://github.com/hwqdt/Demos/tree/master/src/Catcher.AndroidDemo