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;
}
非異步
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM