当前位置:   article > 正文

如何对HttpWebRequest异步调用?

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();
        }
        private static void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            Console.WriteLine("Please enter the input data to be posted:");
            string postData = Console.ReadLine();
 
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            postStream.Write(byteArray, 0, postData.Length);
            postStream.Close();
            allDone.Set();
        }
   也在网上搜了些资料,但还是找不到更好的办法,有懂的吗?知道的回复一下,谢谢!
 
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/259484
推荐阅读
相关标签
  

闽ICP备14008679号