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; }
        }


    }
}

调用:

Reclaim.ai
Reclaim.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不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
AO3官网入口与中文阅读设置 AO3网页版使用与访问
AO3官网入口与中文阅读设置 AO3网页版使用与访问

本专题围绕 Archive of Our Own(AO3)官网入口展开,系统整理 AO3 最新可用官网地址、网页版访问方式、正确打开链接的方法,并详细讲解 AO3 中文界面设置、阅读语言切换及基础使用流程,帮助用户稳定访问 AO3 官网,高效完成中文阅读与作品浏览。

17

2026.02.02

主流快递单号查询入口 实时物流进度一站式追踪专题
主流快递单号查询入口 实时物流进度一站式追踪专题

本专题聚合极兔快递、京东快递、中通快递、圆通快递、韵达快递等主流物流平台的单号查询与运单追踪内容,重点解决单号查询、手机号查物流、官网入口直达、包裹进度实时追踪等高频问题,帮助用户快速获取最新物流状态,提升查件效率与使用体验。

6

2026.02.02

Golang WebAssembly(WASM)开发入门
Golang WebAssembly(WASM)开发入门

本专题系统讲解 Golang 在 WebAssembly(WASM)开发中的实践方法,涵盖 WASM 基础原理、Go 编译到 WASM 的流程、与 JavaScript 的交互方式、性能与体积优化,以及典型应用场景(如前端计算、跨平台模块)。帮助开发者掌握 Go 在新一代 Web 技术栈中的应用能力。

1

2026.02.02

PHP Swoole 高性能服务开发
PHP Swoole 高性能服务开发

本专题聚焦 PHP Swoole 扩展在高性能服务端开发中的应用,系统讲解协程模型、异步IO、TCP/HTTP/WebSocket服务器、进程与任务管理、常驻内存架构设计。通过实战案例,帮助开发者掌握 使用 PHP 构建高并发、低延迟服务端应用的工程化能力。

2

2026.02.02

Java JNI 与本地代码交互实战
Java JNI 与本地代码交互实战

本专题系统讲解 Java 通过 JNI 调用 C/C++ 本地代码的核心机制,涵盖 JNI 基本原理、数据类型映射、内存管理、异常处理、性能优化策略以及典型应用场景(如高性能计算、底层库封装)。通过实战示例,帮助开发者掌握 Java 与本地代码混合开发的完整流程。

1

2026.02.02

go语言 注释编码
go语言 注释编码

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

61

2026.01.31

go语言 math包
go语言 math包

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

53

2026.01.31

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

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

26

2026.01.31

golang 循环遍历
golang 循环遍历

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

31

2026.01.31

热门下载

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

精品课程

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

共94课时 | 8.3万人学习

C 教程
C 教程

共75课时 | 4.4万人学习

C++教程
C++教程

共115课时 | 15.3万人学习

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

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