我见过这么多的发送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