一 HttpWebReques
1,HttpWebRequest是个抽象类,所以无法new的,需要调用HttpWebRequest.Create();
2,其Method指定了请求类型,这里用的GET,还有POST;也可以指定ConentType;
3,其请求的Uri必须是绝对地址;
4,其请求是异步回调方式的,从BeginGetResponse开始,并通过AsyncCallback指定回调方法;
二 WebClient
1,WebClient 方式使用基于事件的异步编程模型,在HTTP响应返回时引发的WebClient回调是在UI线程中调用的,因此可用于更新UI元素的属性,
例如把 HTTP响应中的数据绑定到UI的指定控件上进行显示。HttpWebRequest是基于后台进程运行的,回调不是UI线程,所以不能直接对UI进行操作,通常使用Dispatcher.BeginInvoke()跟界面进行通讯。
 1 //body是要传递的参数,格式"roleId=1&uid=2"
 2 //post的cotentType填写:
 3 //"application/x-www-form-urlencoded"
 4 //soap填写:"text/xml; charset=utf-8"
 5     public static string PostHttp(string url, string body, string contentType)
 6     {
 7         HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
 8 
 9         httpWebRequest.ContentType = contentType;
10         httpWebRequest.Method = "POST";
11         httpWebRequest.Timeout = 20000;
12 
13         byte[] btBodys = Encoding.UTF8.GetBytes(body);
14         httpWebRequest.ContentLength = btBodys.Length;
15         httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
16 
17         HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
18         StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
19         string responseContent = streamReader.ReadToEnd();
20 
21         httpWebResponse.Close();
22         streamReader.Close();
23         httpWebRequest.Abort();
24         httpWebResponse.Close();
25 
26         return responseContent;
27     }
28 
29 POST方法(httpWebRequest)
POST方法(httpWebRequest)

相关文章: