Canonical HTTP POST代码?

我见过很多发送httppost的实现,不可否认,我并不完全了解底层细节,知道需要什么。

在C#.NET 3.5中发送HTTP POST的简洁/正确/规范代码是什么?

我想要一个通用的方法

public string SendPost(string url, string data) 

可以添加到库中并始终用于发布数据,并将返回服务器响应。

我相信这个简单的版本就是

 var client = new WebClient(); return client.UploadString(url, data); 

System.Net.WebClient类具有其他有用的方法,可让您下载或上载字符串或文件或字节。

不幸的是,(通常)情况下你需要做更多的工作。 例如,上面没有考虑需要对代理服务器进行身份validation的情况(尽管它将使用IE的默认代理配置)。

此外,WebClient不支持上传多个文件或设置(某些特定的)标题,有时您将不得不更深入地使用

而是System.Web.HttpWebRequestSystem.Net.HttpWebResponse

正如其他人所说, WebClient.UploadString (或UploadData )是要走的路。

但是,内置的WebClient有一个主要缺点:您几乎无法控制场景后面使用的WebRequest (cookie,身份validation,自定义标头……)。 解决该问题的一种简单方法是创建自定义WebClient并覆盖GetWebRequest方法。 然后,您可以在发送请求之前自定义请求(您可以通过重写GetWebResponse来执行相同的响应)。 以下是一个支持cookie的WebClient 示例 。 这很简单,让我想知道为什么内置的WebClient不能开箱即用……

相比:

 // create a client object using(System.Net.WebClient client = new System.Net.WebClient()) { // performs an HTTP POST client.UploadString(url, xml); } 

 string HttpPost (string uri, string parameters) { // parameters: name1=value1&name2=value2 WebRequest webRequest = WebRequest.Create (uri); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes (parameters); Stream os = null; try { // send the Post webRequest.ContentLength = bytes.Length; //Count bytes to send os = webRequest.GetRequestStream(); os.Write (bytes, 0, bytes.Length); //Send it } catch (WebException ex) { MessageBox.Show ( ex.Message, "HttpPost: Request error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } finally { if (os != null) { os.Close(); } } try { // get the response WebResponse webResponse = webRequest.GetResponse(); if (webResponse == null) { return null; } StreamReader sr = new StreamReader (webResponse.GetResponseStream()); return sr.ReadToEnd ().Trim (); } catch (WebException ex) { MessageBox.Show ( ex.Message, "HttpPost: Response error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } return null; } // end HttpPost 

为什么人们使用/写后者?