• 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;
    }
    非异步
     
  • 相关阅读:
    js rsa sign使用笔记(加密,解密,签名,验签)
    金额的计算
    常用js方法集合
    sourceTree 的使用
    node-- express()模块
    详细讲解vue.js里的父子组件通信(props和$emit)
    Vue -- vue-cli webpack打包开启Gzip 报错
    es6函数的rest参数和拓展运算符(...)的解析
    js中判断对象数据类型的方法
    vue学习之vue基本功能初探
  • 原文地址:https://www.cnblogs.com/sajiao/p/10607783.html
Copyright © 2020-2023  润新知