菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
273
0

C# HTTP请求 异步(async await)

原创
05/13 14:22
阅读数 67578
        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;
}
非异步
 

发表评论

0/200
273 点赞
0 评论
收藏
为你推荐 换一批