您好,欢迎访问一九零五行业门户网

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); }
以上就是c# 异步发送http请求的示例代码详细介绍的内容。
其它类似信息

推荐信息