搜尋
首頁後端開發C#.Net教程C# 非同步發送HTTP請求的範例程式碼詳細介紹

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<AsynHttpContext, Exception> _action;
        private Stopwatch _watch = new Stopwatch();
        private byte[] requestBytes;


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


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


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


        /// <summary>
        /// 用于http get
        /// </summary>
        /// <param name="req">HttpWebRequest</param>
        /// <param name="action"></param>
        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);
            }
        }


        /// <summary>
        /// 用于POST
        /// </summary>
        /// <param name="req">HttpWebRequest</param>
        /// <param name="reqBytes">post bytes</param>
        /// <param name="action">call back</param>
        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<byte>(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<byte>(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;
        /// <summary>
        /// 偏移量
        /// </summary>
        public int Offset
        {
            get { return _offset; }
            set { _offset = value; }
        }


        int _count;
        /// <summary>
        /// 读取次数
        /// </summary>
        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }
        int _unreadLength;
        /// <summary>
        /// 没有读取的长度
        /// </summary>
        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; }
        }


    }
}


#

  Action<string, Exception> OnResponseGet = new Action<string, Exception>((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<AsynHttpContext>.Instance.Register(asynContext);


                AysncHttpRequestHelperV2.Post(asynContext, data, new Action<AsynHttpContext, Exception>((httpContext, ex) =>
                {
                    try
                    {
                        //       TransactionManager<AsynHttpContext>.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);
            }

AsyncStream.cs


#rrreee

#rrreee
AsyncStream.cs

####rrreee###### #呼叫:######rrreee### 以上就是C# 非同步發送HTTP請求的範例程式碼詳細介紹的內容,更多相關內容請關注PHP中文網(www.php.cn)! ################
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
從網絡到桌面:C#.NET的多功能性從網絡到桌面:C#.NET的多功能性Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#.NET與未來:適應新技術C#.NET與未來:適應新技術Apr 14, 2025 am 12:06 AM

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

c#.net適合您嗎?評估其適用性c#.net適合您嗎?評估其適用性Apr 13, 2025 am 12:03 AM

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

.NET中的C#代碼:探索編程過程.NET中的C#代碼:探索編程過程Apr 12, 2025 am 12:02 AM

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#.NET:探索核心概念和編程基礎知識C#.NET:探索核心概念和編程基礎知識Apr 10, 2025 am 09:32 AM

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。

測試C#.NET應用程序:單元,集成和端到端測試測試C#.NET應用程序:單元,集成和端到端測試Apr 09, 2025 am 12:04 AM

C#.NET應用的測試策略包括單元測試、集成測試和端到端測試。 1.單元測試確保代碼的最小單元獨立工作,使用MSTest、NUnit或xUnit框架。 2.集成測試驗證多個單元組合的功能,常用模擬數據和外部服務。 3.端到端測試模擬用戶完整操作流程,通常使用Selenium進行自動化測試。

高級C#.NET教程:ACE您的下一次高級開發人員面試高級C#.NET教程:ACE您的下一次高級開發人員面試Apr 08, 2025 am 12:06 AM

C#高級開發者面試需要掌握異步編程、LINQ、.NET框架內部工作原理等核心知識。 1.異步編程通過async和await簡化操作,提升應用響應性。 2.LINQ以SQL風格操作數據,需注意性能。 3..NET框架的CLR管理內存,垃圾回收需謹慎使用。

C#.NET面試問題和答案:提高您的專業知識C#.NET面試問題和答案:提高您的專業知識Apr 07, 2025 am 12:01 AM

C#.NET面試問題和答案包括基礎知識、核心概念和高級用法。 1)基礎知識:C#是微軟開發的面向對象語言,主要用於.NET框架。 2)核心概念:委託和事件允許動態綁定方法,LINQ提供強大查詢功能。 3)高級用法:異步編程提高響應性,表達式樹用於動態代碼構建。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能