我見過這麼多的發送http帖子的實現,但我承認我並不完全理解底層的細節以知道需要什麼。Canonical HTTP POST代碼?
在C#.NET 3.5中發送HTTP POST的簡潔/正確/規範代碼是什麼?
我要像
public string SendPost(string url, string data)
可以添加到庫中,並始終用於發佈數據並返回服務器響應的通用方法。
我見過這麼多的發送http帖子的實現,但我承認我並不完全理解底層的細節以知道需要什麼。Canonical HTTP POST代碼?
在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
類有讓你下載或上傳字符串或文件,或字節其他有用的方法。
不幸的是,有很多情況下你必須做更多的工作。例如,上述例子並不考慮您需要使用代理服務器進行身份驗證的情況(儘管它將使用IE的默認代理配置)。
而且Web客戶端不支持多個文件或設置(一些具體的)頭上傳,有時你會不得不更深入和使用
System.Web.HttpWebRequest
和System.Net.HttpWebResponse
代替。
比較:
// 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
爲什麼使用/寫入後者的人嗎?
通常情況下,因爲我們需要實際修改WebClient類允許的請求,特別是如果您希望更改某些標頭WebClient限制了這樣做的能力,請參閱http://msdn.microsoft.com/ en-us/library/system.net.webclient.headers.aspx – RobV 2009-09-24 15:55:47
正如其他人所說,WebClient.UploadString
(或UploadData
)是要走的路。
但是,內置的WebClient
有一個主要缺點:您幾乎不能控制在場景後面使用的WebRequest
(cookie,驗證,自定義標頭......)。解決該問題的一個簡單方法是創建自定義WebClient
並覆蓋GetWebRequest
方法。然後,您可以在發送請求之前自定義請求(您可以通過覆蓋GetWebResponse
來完成響應)。這裏有一個Cookie-aware WebClient
的an example。這很簡單,它讓我想知道爲什麼內置的WebClient不能處理它的開箱即用...
很酷,感謝您的鏈接! – 2009-09-25 01:27:58
對於WebClient.UploadString +1!關於WebClient的侷限性,有一個簡單的解決方法,請參閱我的回答 – 2009-09-25 00:33:00
我發現自己正在做的一件事是將xml發佈到web服務。 UploadString是這種情況的一個很好的選擇嗎?那編碼呢?它是UTF-16嗎? – User 2009-09-25 07:07:07
您可以使用WebClient的Encoding屬性將編碼設置爲UFT-16。 – 2009-09-28 02:47:21