0

0

C# 异步发送HTTP请求的示例代码详细介绍

黄舟

黄舟

发布时间:2017-03-03 11:22:40

|

4392人浏览过

|

来源于php中文网

原创

http异步请求

asynchttprequesthelperv2.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Imps.Services.CommonV4;
using System.Diagnostics;
using System.Net;
using System.IO;


namespace Imps.Services.IDCService.Utility
{
    public class AysncHttpRequestHelperV2
    {
        public static readonly ITracing _logger = TracingManager.GetTracing(typeof(AysncHttpRequestHelperV2));


        private AsynHttpContext _context;
        private byte[] buffer;
        private const int DEFAULT_LENGTH = 1024 * 512;
        private const int DEFAULT_POS_LENGTH = 1024 * 16;
        private bool notContentLength = false;
        private Action _action;
        private Stopwatch _watch = new Stopwatch();
        private byte[] requestBytes;


        private AysncHttpRequestHelperV2(HttpWebRequest request, Action callBack)
            : this(new AsynHttpContext(request), callBack)
        {
        }
        private AysncHttpRequestHelperV2(AsynHttpContext context, Action callBack)
        {
            this._context = context;
            this._action = callBack;
            this._watch = new Stopwatch();
        }


        public static void Get(HttpWebRequest request, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(request, callBack);
            proxy.SendRequest();
        }
        public static void Get(AsynHttpContext context, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(context, callBack);
            proxy.SendRequest();
        }


        public static void Post(HttpWebRequest request, byte[] reqBytes, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(request, callBack);
            proxy.SendRequest(reqBytes);
        }
        public static void Post(AsynHttpContext context, byte[] reqBytes, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(context, callBack);
            proxy.SendRequest(reqBytes);
        }
        public static void Post(HttpWebRequest request, string reqStr, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(request, callBack);
            proxy.SendRequest(Encoding.UTF8.GetBytes(reqStr));
        }
        public static void Post(AsynHttpContext context, string reqStr, Action callBack)
        {
            AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2(context, callBack);
            proxy.SendRequest(Encoding.UTF8.GetBytes(reqStr));
        }


        /// 
        /// 用于http get
        /// 
        /// HttpWebRequest
        /// 
        private void SendRequest()
        {
            try
            {
                _watch.Start();
               
                _context.RequestTime = DateTime.Now;
                IAsyncResult asyncResult = _context.AsynRequest.BeginGetResponse(RequestCompleted, _context);
            }
            catch (Exception e)
            {
                _logger.Error(e, "send request exception.");
                EndInvoke(_context, e);
            }
        }


        /// 
        /// 用于POST
        /// 
        /// HttpWebRequest
        /// post bytes
        /// call back
        private void SendRequest(byte[] reqBytes)
        {
            try
            {
                _watch.Start();
                requestBytes = reqBytes;
                _context.AsynRequest.Method = "POST";
                _context.RequestTime = DateTime.Now;


                IAsyncResult asyncRead = _context.AsynRequest.BeginGetRequestStream(asynGetRequestCallBack, _context.AsynRequest);
            }
            catch (Exception e)
            {
                _logger.Error(e, "send request exception.");
                EndInvoke(_context, e);
            }
        }


        private void asynGetRequestCallBack(IAsyncResult asyncRead)
        {
            try
            {
                HttpWebRequest request = asyncRead.AsyncState as HttpWebRequest;
                Stream requestStream = request.EndGetRequestStream(asyncRead);
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();
                SendRequest();
            }
            catch (Exception e)
            {
                _logger.Error(e, "GetRequestCallBack exception.");
                EndInvoke(_context, e);
            }
        }
        private void asynGetRequestCallBack2(IAsyncResult asyncRead)
        {
            try
            {
                HttpWebRequest request = asyncRead.AsyncState as HttpWebRequest;
                Stream requestStream = request.EndGetRequestStream(asyncRead);
                requestStream.BeginWrite(requestBytes, 0, requestBytes.Length, endStreamWrite, requestStream);
            }
            catch (Exception e)
            {
                _logger.Error(e, "GetRequestCallBack exception.");
                EndInvoke(_context, e);
            }
        }
        private void endStreamWrite(IAsyncResult asyncWrite)
        {
            try
            {
                Stream requestStream = asyncWrite.AsyncState as Stream;
                requestStream.EndWrite(asyncWrite);
                requestStream.Close();
                SendRequest();
            }
            catch (Exception e)
            {
                _logger.Error(e, "GetRequestCallBack exception.");
                EndInvoke(_context, e);
            }
        }


        private void RequestCompleted(IAsyncResult asyncResult)
        {
            AsynHttpContext _context = asyncResult.AsyncState as AsynHttpContext;
            try
            {
                if (asyncResult == null) return;
                _context.AsynResponse = (HttpWebResponse)_context.AsynRequest.EndGetResponse(asyncResult);
            }
            catch (WebException e)
            {
                _logger.Error(e, "RequestCompleted WebException.");
                _context.AsynResponse = (HttpWebResponse)e.Response;
                if (_context.AsynResponse == null)
                {
                    EndInvoke(_context, e);
                    return;
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "RequestCompleted exception.");
                EndInvoke(_context, e);
                return;
            }
            try
            {
                AsynStream stream = new AsynStream(_context.AsynResponse.GetResponseStream());
                stream.Offset = 0;
                long length = _context.AsynResponse.ContentLength;
                if (length < 0)
                {
                    length = DEFAULT_LENGTH;
                    notContentLength = true;
                }
                buffer = new byte[length];
                stream.UnreadLength = buffer.Length;
                IAsyncResult asyncRead = stream.NetStream.BeginRead(buffer, 0, stream.UnreadLength, new AsyncCallback(ReadCallBack), stream);
            }
            catch (Exception e)
            {
                _logger.Error(e, "BeginRead exception.");
                EndInvoke(_context, e);
            }
        }


        private void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {
                AsynStream stream = asyncResult.AsyncState as AsynStream;
                int read = 0;
                if (stream.UnreadLength > 0)
                    read = stream.NetStream.EndRead(asyncResult);
                if (read > 0)
                {
                    stream.Offset += read;
                    stream.UnreadLength -= read;
                    stream.Count++;
                    if (notContentLength && stream.Offset >= buffer.Length)
                    {
                        Array.Resize(ref buffer, stream.Offset + DEFAULT_POS_LENGTH);
                        stream.UnreadLength = DEFAULT_POS_LENGTH;
                    }
                    IAsyncResult asyncRead = stream.NetStream.BeginRead(buffer, stream.Offset, stream.UnreadLength, new AsyncCallback(ReadCallBack), stream);
                }
                else
                {
                    _watch.Stop();
                    stream.NetStream.Dispose();
                    if (buffer.Length != stream.Offset)
                        Array.Resize(ref buffer, stream.Offset);
                    _context.ExecTime = _watch.ElapsedMilliseconds;
                    _context.SetResponseBytes(buffer);
                    _action.Invoke(_context, null);
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "ReadCallBack exception.");
                EndInvoke(_context, e);
            }
        }


        private void EndInvoke(AsynHttpContext _context, Exception e)
        {
            try
            {
                _watch.Stop();
                _context.ExecTime = _watch.ElapsedMilliseconds;
                _action.Invoke(_context, e);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "EndInvoke exception.");
                _action.Invoke(null, ex);
            }
        }


    }
}

AsyncHttpContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;


namespace AsyncHttpRequestDemo
{
    public enum AsynStatus { Begin, TimeOut, Runing, Completed }


    public class AsynHttpContext : IDisposable
    {
        private HttpWebRequest _asynRequest;
        private HttpWebResponse _asynResponse;
        private DateTime _requestTime;
        private long _execTime;
        bool isDisposable = false;
        private byte[] _rspBytes;




        public long ExecTime
        {
            get { return _execTime; }
            set { _execTime = value; }
        }
        public byte[] ResponseBytes
        {
            get { return _rspBytes; }
        }


        public HttpWebRequest AsynRequest
        {
            get { return _asynRequest; }
        }
        public HttpWebResponse AsynResponse
        {
            get { return _asynResponse; }
            set { _asynResponse = value; }
        }
        public DateTime RequestTime
        {
            get { return _requestTime; }
            set { _requestTime = value; }
        }
        private AsynHttpContext() { }
        public AsynHttpContext(HttpWebRequest req)
        {
            _asynRequest = req;
        }
        public void SetResponseBytes(byte[] bytes)
        {
            _rspBytes = bytes;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        public void OnTimeOut()
        {
            if (_asynRequest != null)
                _asynRequest.Abort();
            this.Dispose();
        }
        private void Dispose(bool disposing)
        {
            if (!isDisposable)
            {
                if (disposing)
                {
                    if (_asynRequest != null)
                        _asynRequest.Abort();
                    if (_asynResponse != null)
                        _asynResponse.Close();
                }
            }
            isDisposable = true;
        }
        ~AsynHttpContext()
        {
            Dispose(false);
        }
    }
}

AsyncStream.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace AsyncHttpRequestDemo
{
    public class AsynStream
    {
        int _offset;
        /// 
        /// 偏移量
        /// 
        public int Offset
        {
            get { return _offset; }
            set { _offset = value; }
        }


        int _count;
        /// 
        /// 读取次数
        /// 
        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }
        int _unreadLength;
        /// 
        /// 没有读取的长度
        /// 
        public int UnreadLength
        {
            get { return _unreadLength; }
            set { _unreadLength = value; }
        }
        public AsynStream(int offset, int count, Stream netStream)
        {
            _offset = offset;
            _count = count;
            _netStream = netStream;
        }
        public AsynStream(Stream netStream)
        {
            _netStream = netStream;
        }




        Stream _netStream;


        public Stream NetStream
        {
            get { return _netStream; }
            set { _netStream = value; }
        }


    }
}

调用:

FaceSwapper
FaceSwapper

FaceSwapper是一款AI在线换脸工具,可以让用户在照片和视频中无缝交换面孔。

下载
  Action OnResponseGet = new Action((s, ex) =>
            {
                if (ex != null)
                {
                    string exInfo = ex.Message;
                }
                string ret = s;
            });
            try
            {
                string strRequestXml = "hello";
                int timeout = 15000;
                string contentType = "text/xml";
                string url = "http://192.168.110.191:8092/getcontentinfo/";
                UTF8Encoding encoding = new UTF8Encoding();
                byte[] data = encoding.GetBytes(strRequestXml);


                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                myHttpWebRequest.Timeout = timeout;
                myHttpWebRequest.Method = "POST";
                myHttpWebRequest.ContentType = contentType;
                myHttpWebRequest.ContentLength = data.Length;


                //if (headers != null && headers.Count > 0)
                //{
                //    foreach (var eachheader in headers)
                //    {
                //        myHttpWebRequest.Headers.Add(eachheader.Key, eachheader.Value);
                //    }
                //}


             
                
                AsynHttpContext asynContext = new AsynHttpContext(myHttpWebRequest);
                // string tranKey = TransactionManager.Instance.Register(asynContext);


                AysncHttpRequestHelperV2.Post(asynContext, data, new Action((httpContext, ex) =>
                {
                    try
                    {
                        //       TransactionManager.Instance.Unregister(tranKey);




                        if (ex != null)
                        {
                            //    _tracing.Error(ex, "Exception Occurs On AysncHttpRequestHelperV2 Post Request.");
                            OnResponseGet(null, ex);
                        }
                        else
                        {
                            string rspStr = Encoding.UTF8.GetString(httpContext.ResponseBytes);
                            //  _tracing.InfoFmt("Aysnc Get Response Content : {0}", rspStr);
                            OnResponseGet(rspStr, null);
                        }
                    }
                    catch (Exception ex2)
                    {
                        //  _tracing.ErrorFmt(ex2, "");
                        OnResponseGet(null, ex2);
                    }
                }));
            }


            catch (Exception ex)
            {
                // _tracing.Error(ex, "Exception Occurs On Aysnc Post Request.");
                OnResponseGet(null, ex);
            }

 以上就是C# 异步发送HTTP请求的示例代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

2

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

0

2026.01.31

Golang人工智能合集
Golang人工智能合集

本专题整合了Golang人工智能相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

76

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

73

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

67

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

19

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
C# 教程
C# 教程

共94课时 | 8.1万人学习

C 教程
C 教程

共75课时 | 4.3万人学习

C++教程
C++教程

共115课时 | 15万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号