Http异步发送之HttpWebRequest的BeginGetResponse

关于http异步发送,一开始我的做法都是用thread或者task去完成的;后来发现HttpWebRequest本身就提供一个异步的方法。

总感觉.Net自己提供的异步方法可能要优于我们自己用线程去实现的好;

当然这只是我的猜想。个人感觉如果有大量异步发送还是用HttpWebRequest本身提供的异步方法好。

自己封装了下HttpWebRequest的异步请求。

  1         /// <summary>
  2         /// http异步请求
  3         /// </summary>
  4         /// <param name="url">url</param>
  5         /// <param name="reqMethod">请求方法 GET、POST</param>
  6         /// <param name="callback">回调函数</param>
  7         /// <param name="ob">回传对象</param>
  8         /// <param name="postData">post数据</param>
  9         public static void HttpAsyncRequest(string url, string reqMethod, AsyRequetCallback callback, object ob = null, string postData = "")
 10         {
 11             Stream requestStream = null;
 12             try
 13             {
 14                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
 15                 request.ContentType = "application/x-www-form-urlencoded";
 16                 request.Method = reqMethod;
 17                 if (reqMethod.ToUpper() == "POST")
 18                 {
 19                     byte[] bytes = Encoding.UTF8.GetBytes(postData);
 20                     request.ContentLength = bytes.Length;
 21                     requestStream = request.GetRequestStream();
 22                     requestStream.Write(bytes, 0, bytes.Length);
 23                 }
 24                 //开始调用异步请求 
 25                 //AsyResultTag 是自定义类 用于传递调用时信息 其中HttpWebRequest 是必须传递对象。
 26                 //因为回调需要用HttpWebRequest来获取HttpWebResponse 
 27                 request.BeginGetResponse(new AsyncCallback(HttpCallback), new AsyResultTag() { obj = ob, callback = callback, req = request });
 28             }
 29             catch (Exception ex)
 30             {
 31                 throw ex;
 32             }
 33             finally
 34             {
 35                 if (requestStream != null)
 36                 {
 37                     requestStream.Close();
 38                 }
 39             }
 40         }
 41 
 42 
 43         /// <summary>
 44         /// http请求回调 由.net内部调用 参数必须为IAsyncResult
 45         /// </summary>
 46         /// <param name="asynchronousResult">http回调时回传对象</param>
 47         private static void HttpCallback(IAsyncResult asynchronousResult)
 48         {
 49             int statusCode = 0;
 50             string retString = "";
 51             AsyResultTag tag = new AsyResultTag();
 52             WebException webEx = null;
 53             try
 54             {
 55                 //获取请求时传递的对象
 56                 tag = asynchronousResult.AsyncState as AsyResultTag;
 57                 HttpWebRequest req = tag.req;
 58                 //获取异步返回的http结果
 59                 HttpWebResponse response = req.EndGetResponse(asynchronousResult) as HttpWebResponse;
 60                 Stream myResponseStream = response.GetResponseStream();
 61                 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
 62                 retString = myStreamReader.ReadToEnd();
 63                 myStreamReader.Close();
 64                 myResponseStream.Close();
 65                 statusCode = ((int)response.StatusCode);
 66 
 67             }
 68             catch (WebException ex)
 69             {
 70                 if ((HttpWebResponse)ex.Response != null)
 71                 {
 72                     statusCode = ((int)((HttpWebResponse)ex.Response).StatusCode);
 73                 }
 74                 
 75                 webEx = ex;
 76             }
 77             //调用外部回调 即最外层的回调
 78             tag.callback(tag.obj, retString, statusCode, webEx);
 79 
 80         }
 81 
 82        /// <summary>
 83        /// 异步请求回调委托
 84        /// </summary>
 85       /// <param name="asyObj">回传对象</param>
 86       /// <param name="resStr">http响应结果</param>
 87       /// <param name="statusCode">http状态码</param>
 88       /// <param name="webEx">异常</param>
 89       public delegate void AsyRequetCallback(object asyObj, string respStr, int statusCode, WebException webEx);
 90 
 91      /// <summary>
 92      /// 异步返回对象
 93      /// </summary>
 94      class AsyResultTag
 95      {
 96         /// <summary>
 97         /// 回传对象
 98         /// </summary>
 99         public object obj { get; set; }
100         /// <summary>
101         /// 当前httpRequest请求实例
102         /// </summary>
103         public HttpWebRequest req { get; set; }
104         /// <summary>
105         /// 回调函数委托
106         /// </summary>
107         public AsyRequetCallback callback { get; set; }
108      }
AsyRequetCallback 异步回调委托,即要回调的函数原型;说下每个参数的意义:

1、object asyObj:
回传对象,即请求时附带的一个对象,如果没有可以不用传。比如我们当前的这个请求和用户有所关联,如当前的这个请求对应是某个用户的,请求后我要将结果写到这个用户的某个属性下面;这样我们就可以将此用户信息和当前请求一起携带过去。
2、string respStr:当前http返回结果。

3、int statusCode:http状态码,包括出错时的状态码。如404,403等。

4、WebException webEx 异常信息,异常信息也会随着回调传递到前面来,不直接向上抛或者直接log。好处在于,我们可以针对这个异常信息做单独处理。比如某个用户如果碰到什么403或者404我们应该怎么处理,又或者我们可以将错误信息随着当前用户进行保存,很好的跟踪每个用户的发送情况。


 
 

 

转载于:https://www.cnblogs.com/rui1236/p/7103631.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 `HttpWebRequest` 类来发送带有 `form-data` 的 POST 请求。 以下是一个示例代码: ```csharp public static string HttpPostForm(string url, Dictionary<string, object> formData, string boundary) { string result = string.Empty; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { // 添加表单数据 foreach (var item in formData) { if (item.Value is byte[]) { byte[] fileData = (byte[])item.Value; string fileName = item.Key; string fileContentType = "application/octet-stream"; // 写入文件数据 WriteFileData(requestStream, boundary, fileName, fileContentType, fileData); } else { // 写入表单数据 WriteFormData(requestStream, boundary, item.Key, item.Value.ToString()); } } // 写入结束标识 WriteEndBoundary(requestStream, boundary); } // 发送请求 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } return result; } private static void WriteFormData(Stream stream, string boundary, string key, string value) { string formDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n"; string formData = string.Format(formDataTemplate, boundary, key, value); byte[] formDataBytes = Encoding.UTF8.GetBytes(formData); stream.Write(formDataBytes, 0, formDataBytes.Length); } private static void WriteFileData(Stream stream, string boundary, string fileName, string fileContentType, byte[] fileData) { string fileDataTemplate = "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n"; string fileDataHeader = string.Format(fileDataTemplate, boundary, "file", fileName, fileContentType); byte[] fileDataHeaderBytes = Encoding.UTF8.GetBytes(fileDataHeader); stream.Write(fileDataHeaderBytes, 0, fileDataHeaderBytes.Length); stream.Write(fileData, 0, fileData.Length); byte[] fileDataEndBytes = Encoding.UTF8.GetBytes("\r\n"); stream.Write(fileDataEndBytes, 0, fileDataEndBytes.Length); } private static void WriteEndBoundary(Stream stream, string boundary) { string endBoundaryTemplate = "--{0}--\r\n"; string endBoundary = string.Format(endBoundaryTemplate, boundary); byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(endBoundary); stream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); } ``` 其中,`HttpPostForm` 方法用于发送 POST 请求,接收一个 url、一个表单数据字典、一个边界字符串作为参数。在方法内部,我们首先设置请求方法和请求头,然后通过 `GetRequestStream` 方法获取请求流。在请求流中,我们遍历表单数据字典,将表单数据和文件数据分别写入请求流中,最后写入结束标识。最后,我们通过 `GetResponse` 方法获取响应,并将响应内容读取出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值