Example code for sending HTTP requests asynchronously in C # details

Source: Internet
Author: User
Tags call back
HTTP Asynchronous request

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 (AYSNCHTTPR        equestHelperV2));        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): t His (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> Callbac            k) {AysncHttpRequestHelperV2 proxy = new AysncHttpRequestHelperV2 (request, callBack); Proxy.        SendRequest (reqbytes); } public static void Post (Asynhttpcontext context, byte[] reqbytes, Action<asynhttpcontext, exception> callBack) {Aysnchttprequesthel            PerV2 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>//For HTTP GET//</summary>//<param name= "req" >httpwebr equest</param>//<param name= "action" &Gt;</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>//For post///</summary>//<param name= "req" >htt pwebrequest</param>//<param name= "reqbytes" >post bytes</param>//<param name= "Acti                On ">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:id        isposable {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 (Dispo                    Sing) {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>///offset///</summary> public int Offset {get {return _ _ Offset        } set {_offset = value;}        } int _count; <summary>///read///</summary> public int Count {get {return _ _ Count        } set {_count = value;}        } int _unreadlength; <summary>///No Read length///</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;} }    }}

Called:

  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 &GT        0)//{//foreach (var eachheader in headers)//{// MYHTTPWEBREQUEST.HEADERS.ADD (Eachheader. Key, Eachheader.                Value); }//} Asynhttpcontext Asyncontext = new Asynhttpcontext (m                Yhttpwebrequest); string trankey = Transactionmanager<asynhttpcontext>.                Instance.register (Asyncontext); Aysnchttprequesthelperv2.post (Asyncontext, data, New Action<asynhttpcontext, exception> (HttpContext, ex) = > {try {//Transactionmanager<as Ynhttpcontext>.                        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.E                        RRORFMT (Ex2, "");                    Onresponseget (null, EX2);            }                })); } catch (Exception ex) {//_tracing.                Error (ex, "Exception occurs on AYSNC Post Request.");            Onresponseget (null, ex); }

The above is the C # asynchronous send HTTP request sample code details of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.