赞
踩
在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("获取失败.");
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。