欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# HTTP请求 异步(async await)

程序员文章站 2024-01-28 12:17:16
...
        static void Main(string[] args)
        {
            new Task(() =>
            {
                Invoke();
            }).Start();
            Console.WriteLine("我是主线程");
            Console.ReadKey();
        }

        public static async void Invoke()
        {
            var result = Keep();
            Console.WriteLine("执行其他的");
            string str = await result;  //等待返回
            Console.WriteLine(str);  //输出返回
        }

        public static async Task<string> Keep()
        {
            HttpWebRequest request = WebRequest.Create("http:/*****************") as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";     //这里一定不要忘记了 我排查了好久 发现这里没有写这一句  弄的怀疑人生了 后来通过抓包对比 才发现这个差距  粗心了
            string data = "userId=7c509e59-9179-4fc3-b00a-a33007b1068e&agentId=2acbf00f-aa58-44f6-88c8-6d7027b78a7f&companyId=64436ad0-8ef4-430a-b6a4-08cac3b19c0a&versionTime=1553654309167";
            byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
            request.ContentLength = buf.Length;
            Stream newStream = request.GetRequestStream();
            newStream.Write(buf, 0, buf.Length);
            newStream.Close();
            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string result = reader.ReadToEnd();
            return result;
        }

 如果你不写  request.ContentType   那么用下面的这种也可以   

        static void Main(string[] args)
        {
            new Task(() =>
            {
                Invoke();
            }).Start();
            Console.WriteLine("我是主线程");
            Console.ReadKey();
        }

        public static async void Invoke()
        {
            var result = Keep();
            Console.WriteLine("执行其他的");
            string str = await result;  //等待返回
            Console.WriteLine(str);  //输出返回
        }

        public static async Task<string> Keep()
        {
            string url = "http://message.sungoin.com/platform-message/getPlatformClientMsg";
            string data = "userId=7c509e59-9179-4fc3-b00a-a33007b1068e&agentId=2acbf00f-aa58-44f6-88c8-6d7027b78a7f&companyId=64436ad0-8ef4-430a-b6a4-08cac3b19c0a&versionTime=1553654309167";
            url = url + "?" + data;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse;
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string result = reader.ReadToEnd();
            return result.ToString();
        }