关于http异步发送,一开始我的做法都是用thread或者task去完成的;后来发现HttpWebRequest本身就提供一个异步的方法。
总感觉.Net自己提供的异步方法可能要优于我们自己用线程去实现的好;
当然这只是我的猜想。个人感觉如果有大量异步发送还是用HttpWebRequest本身提供的异步方法好。
自己封装了下HttpWebRequest的异步请求。
/// <summary>
/// http异步请求
/// </summary>
/// <param>url</param>
/// <param>请求方法 GET、POST</param>
/// <param>回调函数</param>
/// <param>回传对象</param>
/// <param>post数据</param>
public static void HttpAsyncRequest(string url, string reqMethod, AsyRequetCallback callback, object ob = null, string postData = "")
{
Stream requestStream = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = reqMethod;
if (reqMethod.ToUpper() == "POST")
{
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
}
//开始调用异步请求
//AsyResultTag 是自定义类 用于传递调用时信息 其中HttpWebRequest 是必须传递对象。
//因为回调需要用HttpWebRequest来获取HttpWebResponse
request.BeginGetResponse(new AsyncCallback(HttpCallback), new AsyResultTag() { obj = ob, callback = callback, req = request });
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
}
}
/// <summary>
/// http请求回调 由.net内部调用 参数必须为IAsyncResult
/// </summary>
/// <param>http回调时回传对象</param>
private static void HttpCallback(IAsyncResult asynchronousResult)
{
int statusCode = 0;
string retString = "";
AsyResultTag tag = new AsyResultTag();
WebException webEx = null;
try
{
//获取请求时传递的对象
tag = asynchronousResult.AsyncState as AsyResultTag;
HttpWebRequest req = tag.req;
//获取异步返回的http结果
HttpWebResponse response = req.EndGetResponse(asynchronousResult) as HttpWebResponse;
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
statusCode = ((int)response.StatusCode);