如何对HttpWebRequest异步调用

2025-05-10 03:28:15
推荐回答(1个)
回答1:

如何对HttpWebRequest异步调用?
public static ManualResetEvent allDone = new ManualResetEvent(false);
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");

request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);

allDone.WaitOne();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();

streamResponse.Close();
streamRead.Close();
response.Close();
Console.WriteLine(responseString);
Console.ReadKey();