zoukankan      html  css  js  c++  java
  • 如何对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();
            }
       也在网上搜了些资料,但还是找不到更好的办法,有懂的吗?知道的回复一下,谢谢!
     
  • 相关阅读:
    迭代器和生成器
    案例:复制大文件
    案例:使用seek倒查获取日志文件的最后一行
    Leetcode165. Compare Version Numbers比较版本号
    Leetcode137. Single Number II只出现一次的数字2
    Leetcode129. Sum Root to Leaf Numbers求根到叶子节点数字之和
    Leetcode116. Populating Next Right Pointers in Each Node填充同一层的兄弟节点
    Leetcode114. Flatten Binary Tree to Linked List二叉树展开为链表
    Leetcode113. Path Sum II路径总和2
    C++stl中vector的几种常用构造方法
  • 原文地址:https://www.cnblogs.com/SanMaoSpace/p/2118128.html
Copyright © 2011-2022 走看看