一、前言
回忆到上篇 《Xamarin.Android再体验之简单的登录Demo》 做登录时,用的是GET的请求,还用的是同步,
于是现在将其简单的改写,做了个简单的封装,包含基于HttpClient和HttpWebRequest两种方式的封装。
由于对这一块还不是很熟悉,所以可能不是很严谨。
二、先上封装好的代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace Catcher.AndroidDemo.Common
{
public static class EasyWebRequest
{
/// <summary>
/// send the post request based on HttpClient
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendPostRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = ;
Uri uri = new Uri(requestUrl);
var content = new FormUrlEncodedContent(routeParameters);
try
{
var response = await client.PostAsync(uri, content);
if (response.IsSuccessStatusCode)
{
var stringValue = await response.Content.ReadAsStringAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
} /// <summary>
/// send the get request based on HttpClient
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendGetRequestBasedOnHttpClient(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = ;
//format the url paramters
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
try
{
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var stringValue = await response.Content.ReadAsStringAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
catch (Exception ex)
{
throw ex;
}
return returnValue;
} /// <summary>
/// send the get request based on HttpWebRequest
/// </summary>
/// <param name="requestUrl">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendGetHttpRequestBaseOnHttpWebRequest(string requestUrl, IDictionary<string, string> routeParameters)
{
object returnValue = new object();
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
Uri uri = new Uri(string.Format("{0}?{1}", requestUrl, paramters));
var request = (HttpWebRequest)HttpWebRequest.Create(uri); using (var response = request.GetResponseAsync().Result as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string stringValue = await reader.ReadToEndAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
}
}
return returnValue;
} /// <summary>
/// send the post request based on httpwebrequest
/// </summary>
/// <param name="url">the url you post</param>
/// <param name="routeParameters">the parameters you post</param>
/// <returns>return a response object</returns>
public static async Task<object> SendPostHttpRequestBaseOnHttpWebRequest(string url, IDictionary<string, string> routeParameters)
{
object returnValue = new object(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST"; byte[] postBytes = null;
request.ContentType = "application/x-www-form-urlencoded";
string paramters = string.Join("&", routeParameters.Select(p => p.Key + "=" + p.Value));
postBytes = Encoding.UTF8.GetBytes(paramters.ToString()); using (Stream outstream = request.GetRequestStreamAsync().Result)
{
outstream.Write(postBytes, , postBytes.Length);
} using (HttpWebResponse response = request.GetResponseAsync().Result as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string stringValue = await reader.ReadToEndAsync();
returnValue = JsonObject.Parse(stringValue);
}
}
}
}
return returnValue;
}
}
}
需要说明一下的是,我把这个方法当做一个公共方法抽离到一个单独的类库中
三、添加两个数据服务的方法
[HttpPost]
public ActionResult PostThing(string str)
{
var json = new
{
Code ="",
Msg = "OK",
Val = str
};
return Json(json);
} public ActionResult GetThing(string str)
{
var json = new
{
Code = "",
Msg = "OK",
Val = str
};
return Json(json,JsonRequestBehavior.AllowGet);
}
这两个方法,一个是为了演示post,一个是为了演示get
部署在本地的IIS上便于测试!
四、添加一个Android项目,测试我们的方法
先来看看页面,一个输入框,四个按钮,这四个按钮分别对应一种请求。
然后是具体的Activity代码
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using System.Collections.Generic;
using Catcher.AndroidDemo.Common;
using System.Json; namespace Catcher.AndroidDemo.EasyRequestDemo
{
[Activity(Label = "简单的网络请求Demo", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
EditText txtInput;
Button btnPost;
Button btnGet;
Button btnPostHWR;
Button btnGetHWR;
TextView tv; protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle); SetContentView(Resource.Layout.Main); txtInput = FindViewById<EditText>(Resource.Id.txt_input);
btnPost = FindViewById<Button>(Resource.Id.btn_post);
btnGet = FindViewById<Button>(Resource.Id.btn_get);
btnGetHWR = FindViewById<Button>(Resource.Id.btn_getHWR);
btnPostHWR = FindViewById<Button>(Resource.Id.btn_postHWR);
tv = FindViewById<TextView>(Resource.Id.tv_result); //based on httpclient
btnPost.Click += PostRequest;
btnGet.Click += GetRequest;
//based on httpwebrequest
btnPostHWR.Click += PostRequestByHWR;
btnGetHWR.Click += GetRequestByHWR;
} private async void GetRequestByHWR(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/GetThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendGetHttpRequestBaseOnHttpWebRequest(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest get";
} private async void PostRequestByHWR(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/PostThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendPostHttpRequestBaseOnHttpWebRequest(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpwebrequest post";
} private async void PostRequest(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/PostThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendPostRequestBasedOnHttpClient(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpclient post";
} private async void GetRequest(object sender, EventArgs e)
{
string url = "http://192.168.1.102:8077/User/GetThing";
IDictionary<string, string> routeParames = new Dictionary<string, string>();
routeParames.Add("str", this.txtInput.Text);
var result = await EasyWebRequest.SendGetRequestBasedOnHttpClient(url, routeParames);
var data = (JsonObject)result;
this.tv.Text = "hey," + data["Val"] + ", i am from httpclient get";
}
}
}
OK,下面看看效果图
如果那位大哥知道有比较好用的开源网络框架推荐请告诉我!!
最后放上本次示例的代码:
https://github.com/hwqdt/Demos/tree/master/src/Catcher.AndroidDemo