zoukankan      html  css  js  c++  java
  • C# HTTP请求 异步(async await)

            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();
            }
    

      ============================================2020年6月28日再次编辑=========================================================

       今天看到一篇异步请求的文章,然后点进去一看,发现是自己写的,这感觉有点怪异,

       然后我决定更新一下这个博客吧,都2020了,还用老版本的那种写法,很麻烦的。本来也是很简单的东西,但是看着别扭。

    HttpClient 的异步操作 还是写一下吧! 现在谁还用HttpWebRequest 写起来麻烦的要死
    public async Task<string> Post()
    {
        HttpClient httpClient=new HttpClient();
        HttpContent httpContent = new StringContent("");
        var response = await httpClient.PostAsJsonAsync(url, httpContent);
        var content = await response.Content.ReadAsStringAsync();
        httpContent.Dispose();
    return
    content;
    }
    public async Task<string> Get()
    {
        HttpClient httpClient=new HttpClient();
        var response = await httpClient.GetStringAsync(url);
        httpContent.Dispose();
    }

    这段代码与上面还有有区别的
    区别在于,上述部分是直接一个线程,由这个线程去进行http请求,来达到异步的效果
    这一段呢!是这个http请求这一个过程异步。
    这边就不写具体验证代码了。

    public async string Post()
    {
        HttpClient httpClient=new HttpClient();
        HttpContent httpContent = new StringContent("");
        var response = httpClient.PostAsJsonAsync(url, httpContent);
        var content = response.Content.ReadAsStringAsync();
        httpContent.Dispose();
    return content;
    }
    非异步
     
  • 相关阅读:
    shell脚本空行造成“: not found.sh“报错
    MySQL实现分组排序(8.0版本以下ROW_NUMBER() OVER())
    vscode远程主机
    nginx-ingress-controler改写上下文
    nginx-ingress-controller自定义参数
    kubernetes安装nginx-ingress-controller服务
    二进制kubernetes升级
    C++关键字完整版
    virtio、vhost和 vhost-user
    Tomcat端口占用报错时的排除办法
  • 原文地址:https://www.cnblogs.com/sajiao/p/10607783.html
Copyright © 2011-2022 走看看