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.HttpWebRequest
和System.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
为什么人们使用/写后者?
上述就是C#学习教程:Canonical HTTP POST代码?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1013457.html