1. 程式人生 > >[C#]Http非同步請求

[C#]Http非同步請求

在WinForm設計中,如果直接使用Http請求會導致UI等待Http請求返回而出現介面假死現象。

所以我們可以使用非同步的Http請求來解決這個問題。

1.    設定請求型別併發送請求的方法HttpPost:

    public static void HttpPost(string Url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
 
                request.Method = "POST";//這裡是POST請求,可以改成GET
                request.ContentType = "application/x-www-form-urlencoded";
                request.BeginGetResponse(new AsyncCallback(Compleate), request);
            }
            catch
            {
                MessageBox.Show("請求失敗.");
            }
        }

2.非同步接收返回結果的方法Compleate:

        public static void Compleate(IAsyncResult asyncResult)
        {
            try
            {
                HttpWebRequest req = (asyncResult.AsyncState as HttpWebRequest);
                HttpWebResponse res = req.EndGetResponse(asyncResult) as HttpWebResponse;
                StreamReader reader = new StreamReader(res.GetResponseStream());

                MessageBox.Show(reader.ReadToEnd());
            }
            catch
            {
                MessageBox.Show("獲取失敗.");
            }
        }