如何使用C#中的WebClient发布数据到特定的URL

我需要在WebClient中使用“HTTP Post”将一些数据发布到我拥有的特定URL。

现在,我知道这可以用WebRequest完成,但由于某些原因,我想使用WebClient。 那可能吗? 如果是的话,有人可以给我一些例子或指向正确的方向吗?

我刚刚find解决scheme,而且是比我想象的更容易:)

所以这里是解决scheme:

string URI = "http://www.myurl.com/post.php"; string myParameters = "param1=value1&param2=value2&param3=value3"; using (WebClient wc = new WebClient()) { wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; string HtmlResult = wc.UploadString(URI, myParameters); } 

它的作品像魅力:)

有一个名为UploadValues的内置方法,它可以发送HTTP POST(或任何types的HTTP方法),并以正确的格式数据格式处理请求体的构造(用“&”连接参数和通过url编码转义字符)

 using(WebClient client = new WebClient()) { var reqparm = new System.Collections.Specialized.NameValueCollection(); reqparm.Add("param1", "<any> kinds & of = ? strings"); reqparm.Add("param2", "escaping is already handled"); byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm); string responsebody = Encoding.UTF8.GetString(responsebytes); } 

使用WebClient.UploadStringWebClient.UploadData可以轻松地将数据发送到服务器。 我将使用UploadData显示一个示例,因为UploadString的使用方式与DownloadString相同。

 byte[] bret = client.UploadData("http://www.website.com/post.php", "POST", System.Text.Encoding.ASCII.GetBytes("field1=value1&amp;field2=value2") ); string sret = System.Text.Encoding.ASCII.GetString(bret); 

更多: http : //www.daveamenta.com/2008-05/c-webclient-usage/

 //Making a POST request using WebClient. Function() { WebClient wc = new WebClient(); var URI = new Uri("http://your_uri_goes_here"); //If any encoding is needed. wc.Headers["Content-Type"] = "application/x-www-form-urlencoded"; //Or any other encoding type. //If any key needed wc.Headers["KEY"] = "Your_Key_Goes_Here"; wc.UploadStringCompleted += new UploadStringCompletedEventHandler(wc_UploadStringCompleted); wc.UploadStringAsync(URI,"POST","Data_To_Be_sent"); } void wc__UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) { try { MessageBox.Show(e.Result); //e.result fetches you the response against your POST request. } catch(Exception exc) { MessageBox.Show(exc.ToString()); } } 
 string URI = "site.com/mail.php"; using (WebClient client = new WebClient()) { System.Collections.Specialized.NameValueCollection postData = new System.Collections.Specialized.NameValueCollection() { { "to", emailTo }, { "subject", currentSubject }, { "body", currentBody } }; string pagesource = Encoding.UTF8.GetString(client.UploadValues(URI, postData)); } 
 string URI = "http://www.myurl.com/post.php"; string myParameters = "param1=value1&param2=value2&param3=value3" 

可以简化为

http://www.myurl.com/post.php?param1=value1¶m2=value2¶m3=value3

这总是有效的。 我发现原来的工作和closures。