httpwebrequest客户端请求数据(仿JS里的AJAX写法,使用Lambda表达式)我没有系统的学过C#或者.NET,对一些比较有特点的写法都不太清楚,例如委托和LAMBDA表达式,正好最近一个小程序中使用到,就记录一下。
public delegate void ajaxDeleMethod(string result);
上面的代码是定义一个委托。接下来写一个类似ajax提交请求的部分
public static void Ajax(string method,string url,
Dictionary<string,string> _params,string contentType,CookieContainer cc,
ajaxDeleMethod onSucess,ajaxDeleMethod onError)
{
RequestPackage package = new RequestPackage(url);
package.Method = method;
if (_params != null)
{
foreach (string key in _params.Keys)
{
package.Params.Add(key, _params[key]);
}
}
package.Accept = "*/*";
package.Cookies = cc;
try
{
HttpWebResponse response = Send2(package);
if (response.StatusCode == HttpStatusCode.OK)
{
using (Stream stream = response.GetResponseStream())
{
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
onSucess(sr.ReadToEnd());
}
}
}
catch (Exception ex)
{
onError(ex.StackTrace);
}
}
使用到了一个类RequestPackage类,这个类就是简单的封闭了一下http头信息,有一个send2用于提交请求并接受返回值,原代码如下:
public static HttpWebResponse Send2(RequestPackage package)
{
ArrayList list = new ArrayList();
HttpWebRequest request = null;
HttpWebResponse response = null;
string url = package.RequestURL;
string method = package.Method.ToString().ToLower();
if (package.Method.ToLower() == EHttpMethod.Get.ToString().ToLower())//GET
{
if (package.Params.Count > 0)
url = string.Format("{0}?{1}", url, JoinParams(package.Params));
request = WebRequest.Create(url) as HttpWebRequest;
request.AllowAutoRedirect = false;
request.Accept = package.Accept;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko";
request.CookieContainer = package.Cookies;
request.Referer = package.RefererURL;
request.Method = method;
}
else//POST
{
request = WebRequest.Create(url) as HttpWebRequest;
request.AllowAutoRedirect = false;
string data = JoinParams(package.Params);
byte[] b = package.Encoding.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Accept = package.Accept;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; MALCJS; rv:11.0) like Gecko";
request.CookieContainer = package.Cookies;
request.Referer = package.RefererURL;
request.Method = method;
request.ContentLength = b.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(b, 0, b.Length);
}
}
try
{
//获取服务器返回的资源
response = request.GetResponse() as HttpWebResponse;
return response;
}
catch (WebException wex)
{
HttpWebResponse wr = wex.Response as HttpWebResponse;
return wr;
}
catch (Exception ex)
{
return response;
}
}
ajax的调用方法如下:
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("params", string.Format("{{"num":"{0}"}}", zj));
HttpContext.Ajax("POST","xx/xx/xx.do",dic,"", _cc,
dataJson =>
{
Zjitem data = JsonConvert.DeserializeObject<Zjitem>(dataJson);//先将结果转换为xsddxx对象
if (data != null && data.total > 0)
{
this.gridWL.DataSource = data.rows;
}
},
error => { MessageBox.Show("获取物料明细出错" + error); }
);