C# 实现HttpWebRequest异步调用
我有这个密码C# 实现HttpWebRequest异步调用,c#,asynchronous,httpwebrequest,streamwriter,C#,Asynchronous,Httpwebrequest,Streamwriter,我有这个密码 using (var stream = new StreamWriter(request.GetRequestStream(), Encoding)) stream.Write(body.ToString()); 我需要使它异步。据我所知,这意味着我需要将对request.GetRequestStream()的调用更改为asycronous.BeginGetRequestStream()。我已经看过这个例子,但不知道如何将其应用到这个场景中。有人能帮忙吗?文档中有一个很好的
using (var stream = new StreamWriter(request.GetRequestStream(), Encoding))
stream.Write(body.ToString());
我需要使它异步。据我所知,这意味着我需要将对
request.GetRequestStream()
的调用更改为asycronous.BeginGetRequestStream()
。我已经看过这个例子,但不知道如何将其应用到这个场景中。有人能帮忙吗?文档中有一个很好的例子():
你可以通过这个代码理解 该程序定义了两个类供自己使用,一个是RequestState类,它通过异步调用传递数据,另一个是ClientGetAsync类,它实现对Internet资源的异步请求 RequestState类在调用为请求提供服务的异步方法时保留请求的状态。它包含WebRequest和Stream实例,其中包含对资源的当前请求和响应中接收到的流、包含当前从Internet资源接收到的数据的缓冲区以及包含完整响应的StringBuilder。当AsyncCallback方法注册到WebRequest.BeginGetResponse时,RequestState作为状态参数传递 ClientGetAsync类实现对Internet资源的异步请求,并将结果响应写入控制台。它包含以下列表中描述的方法和属性 allDone属性包含ManualResetEvent类的一个实例,该类发出请求完成的信号 Main()方法读取命令行并开始请求指定的Internet资源。它创建WebRequest wreq和RequestState R,调用BeginGetResponse开始处理请求,然后调用allDone.WaitOne()方法,以便在回调完成之前应用程序不会退出。从Internet资源读取响应后,Main()将其写入控制台,应用程序结束 showusage()方法在控制台上编写一个示例命令行。当命令行上没有提供URI时,Main()将调用它 RespCallBack()方法为Internet请求实现异步回调方法。它创建包含来自Internet资源的响应的WebResponse实例,获取响应流,然后开始异步读取流中的数据 ReadCallBack()方法实现用于读取响应流的异步回调方法。它将从Internet资源接收的数据传输到RequestState实例的ResponseData属性,然后开始响应流的另一个异步读取,直到不再返回更多数据。读取所有数据后,ReadCallBack()关闭响应流并调用allDone.Set()方法,以指示整个响应都存在于ResponseData中
using System;
using System.Net;
using System.Threading;
using System.Text;
using System.IO;
// The RequestState class passes data across async calls.
public class RequestState
{
const int BufferSize = 1024;
public StringBuilder RequestData;
public byte[] BufferRead;
public WebRequest Request;
public Stream ResponseStream;
// Create Decoder for appropriate enconding type.
public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public RequestState()
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(String.Empty);
Request = null;
ResponseStream = null;
}
}
// ClientGetAsync issues the async request.
class ClientGetAsync
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public static void Main(string[] args)
{
if (args.Length < 1)
{
showusage();
return;
}
// Get the URI from the command line.
Uri httpSite = new Uri(args[0]);
// Create the request object.
WebRequest wreq = WebRequest.Create(httpSite);
// Create the state object.
RequestState rs = new RequestState();
// Put the request into the state object so it can be passed around.
rs.Request = wreq;
// Issue the async request.
IAsyncResult r = (IAsyncResult) wreq.BeginGetResponse(
new AsyncCallback(RespCallback), rs);
// Wait until the ManualResetEvent is set so that the application
// does not exit until after the callback is called.
allDone.WaitOne();
Console.WriteLine(rs.RequestData.ToString());
}
public static void showusage() {
Console.WriteLine("Attempts to GET a URL");
Console.WriteLine("\r\nUsage:");
Console.WriteLine(" ClientGetAsync URL");
Console.WriteLine(" Example:");
Console.WriteLine(" ClientGetAsync http://www.contoso.com/");
}
private static void RespCallback(IAsyncResult ar)
{
// Get the RequestState object from the async result.
RequestState rs = (RequestState) ar.AsyncState;
// Get the WebRequest from RequestState.
WebRequest req = rs.Request;
// Call EndGetResponse, which produces the WebResponse object
// that came from the request issued above.
WebResponse resp = req.EndGetResponse(ar);
// Start reading data from the response stream.
Stream ResponseStream = resp.GetResponseStream();
// Store the response stream in RequestState to read
// the stream asynchronously.
rs.ResponseStream = ResponseStream;
// Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead
IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
// Get the RequestState object from AsyncResult.
RequestState rs = (RequestState)asyncResult.AsyncState;
// Retrieve the ResponseStream that was set in RespCallback.
Stream responseStream = rs.ResponseStream;
// Read rs.BufferRead to verify that it contains data.
int read = responseStream.EndRead( asyncResult );
if (read > 0)
{
// Prepare a Char array buffer for converting to Unicode.
Char[] charBuffer = new Char[BUFFER_SIZE];
// Convert byte stream to Char array and then to String.
// len contains the number of characters converted to Unicode.
int len =
rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);
String str = new String(charBuffer, 0, len);
// Append the recently read data to the RequestData stringbuilder
// object contained in RequestState.
rs.RequestData.Append(
Encoding.ASCII.GetString(rs.BufferRead, 0, read));
// Continue reading data until
// responseStream.EndRead returns –1.
IAsyncResult ar = responseStream.BeginRead(
rs.BufferRead, 0, BUFFER_SIZE,
new AsyncCallback(ReadCallBack), rs);
}
else
{
if(rs.RequestData.Length>0)
{
// Display data to the console.
string strContent;
strContent = rs.RequestData.ToString();
}
// Close down the response stream.
responseStream.Close();
// Set the ManualResetEvent so the main thread can exit.
allDone.Set();
}
return;
}
}
使用系统;
Net系统;
使用系统线程;
使用系统文本;
使用System.IO;
//RequestState类通过异步调用传递数据。
公共类请求状态
{
const int BufferSize=1024;
公共数据;
公共字节[]缓冲读取;
公共网络请求;
公共流响应团队;
//为适当的编码类型创建解码器。
公共解码器StreamDecode=Encoding.UTF8.GetDecoder();
公共请求状态()
{
BufferRead=新字节[BufferSize];
RequestData=新的StringBuilder(String.Empty);
请求=null;
ResponseStream=null;
}
}
//ClientGetAsync发出异步请求。
类ClientGetAsync
{
public static ManualResetEvent allDone=新的ManualResetEvent(false);
const int BUFFER_SIZE=1024;
公共静态void Main(字符串[]args)
{
如果(参数长度<1)
{
showusage();
返回;
}
//从命令行获取URI。
Uri httpSite=新Uri(args[0]);
//创建请求对象。
WebRequest wreq=WebRequest.Create(httpSite);
//创建状态对象。
RequestState rs=新的RequestState();
//将请求放入状态对象中,以便可以传递。
rs.请求=wreq;
//发出异步请求。
IAsyncResult r=(IAsyncResult)wreq.BeginGetResponse(
新异步回调(RespCallback,rs);
//等待ManualReset事件设置,以便应用程序
//直到调用回调后才退出。
全部完成。WaitOne();
Console.WriteLine(rs.RequestData.ToString());
}
公共静态void showusage(){
WriteLine(“尝试获取URL”);
Console.WriteLine(“\r\n用法:”);
WriteLine(“ClientGetAsync URL”);
Console.WriteLine(“示例:”);
Console.WriteLine(“ClientGetAsynchttp://www.contoso.com/");
}
专用静态无效响应回调(IAsyncResult ar)
{
//从异步结果中获取RequestState对象。
RequestState rs=(RequestState)ar.AsyncState;
//从RequestState获取WebRequest。
WebRequest req=rs.请求;
//调用EndGetResponse,它生成WebResponse对象
//这来自于上面发出的请求。
WebResponse resp=请求EndGetResponse(ar);
//开始从响应流读取数据。
Stream ResponseStream=resp.GetResponseStream();
//将响应流存储在RequestState中以进行读取
//该流是异步的。
rs.ResponseStream=ResponseStream;
//将rs.BufferRead传递给BeginRead。将数据读入rs.BufferRead
IAsyncResult iarRead=ResponseStream.BeginRead(rs.BufferRead,0,
缓冲区大小,新异步回调(ReadCallBack),rs;
}
私有静态void ReadCallBack(IAsyncResult asyncResult)
{
//从AsyncResult获取RequestState对象。
RequestState rs=(RequestState)asyncResult.AsyncState;
//检索RespCallback中设置的ResponseStream。
s
using System;
using System.Net;
using System.Threading;
using System.Text;
using System.IO;
// The RequestState class passes data across async calls.
public class RequestState
{
const int BufferSize = 1024;
public StringBuilder RequestData;
public byte[] BufferRead;
public WebRequest Request;
public Stream ResponseStream;
// Create Decoder for appropriate enconding type.
public Decoder StreamDecode = Encoding.UTF8.GetDecoder();
public RequestState()
{
BufferRead = new byte[BufferSize];
RequestData = new StringBuilder(String.Empty);
Request = null;
ResponseStream = null;
}
}
// ClientGetAsync issues the async request.
class ClientGetAsync
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
public static void Main(string[] args)
{
if (args.Length < 1)
{
showusage();
return;
}
// Get the URI from the command line.
Uri httpSite = new Uri(args[0]);
// Create the request object.
WebRequest wreq = WebRequest.Create(httpSite);
// Create the state object.
RequestState rs = new RequestState();
// Put the request into the state object so it can be passed around.
rs.Request = wreq;
// Issue the async request.
IAsyncResult r = (IAsyncResult) wreq.BeginGetResponse(
new AsyncCallback(RespCallback), rs);
// Wait until the ManualResetEvent is set so that the application
// does not exit until after the callback is called.
allDone.WaitOne();
Console.WriteLine(rs.RequestData.ToString());
}
public static void showusage() {
Console.WriteLine("Attempts to GET a URL");
Console.WriteLine("\r\nUsage:");
Console.WriteLine(" ClientGetAsync URL");
Console.WriteLine(" Example:");
Console.WriteLine(" ClientGetAsync http://www.contoso.com/");
}
private static void RespCallback(IAsyncResult ar)
{
// Get the RequestState object from the async result.
RequestState rs = (RequestState) ar.AsyncState;
// Get the WebRequest from RequestState.
WebRequest req = rs.Request;
// Call EndGetResponse, which produces the WebResponse object
// that came from the request issued above.
WebResponse resp = req.EndGetResponse(ar);
// Start reading data from the response stream.
Stream ResponseStream = resp.GetResponseStream();
// Store the response stream in RequestState to read
// the stream asynchronously.
rs.ResponseStream = ResponseStream;
// Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead
IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
// Get the RequestState object from AsyncResult.
RequestState rs = (RequestState)asyncResult.AsyncState;
// Retrieve the ResponseStream that was set in RespCallback.
Stream responseStream = rs.ResponseStream;
// Read rs.BufferRead to verify that it contains data.
int read = responseStream.EndRead( asyncResult );
if (read > 0)
{
// Prepare a Char array buffer for converting to Unicode.
Char[] charBuffer = new Char[BUFFER_SIZE];
// Convert byte stream to Char array and then to String.
// len contains the number of characters converted to Unicode.
int len =
rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);
String str = new String(charBuffer, 0, len);
// Append the recently read data to the RequestData stringbuilder
// object contained in RequestState.
rs.RequestData.Append(
Encoding.ASCII.GetString(rs.BufferRead, 0, read));
// Continue reading data until
// responseStream.EndRead returns –1.
IAsyncResult ar = responseStream.BeginRead(
rs.BufferRead, 0, BUFFER_SIZE,
new AsyncCallback(ReadCallBack), rs);
}
else
{
if(rs.RequestData.Length>0)
{
// Display data to the console.
string strContent;
strContent = rs.RequestData.ToString();
}
// Close down the response stream.
responseStream.Close();
// Set the ManualResetEvent so the main thread can exit.
allDone.Set();
}
return;
}
}