令我惊讶的是,从.NET BCL中,我所做的几乎不能像这样简单的事情:
byte[] response = Http.Post
(
url: "http://dork.com/service",
contentType: "application/x-www-form-urlencoded",
contentLength: 32,
content: "home=Cosby&favorite+flavor=flies"
);
上面的该假设代码与数据一起构成了HTTP帖子,并返回了Post
静态课上的方法Http
。
既然我们没有那么简单的东西,那么下一个最佳解决方案是什么?
如何发送带有数据并获取响应内容的HTTP帖子?
答案
using (WebClient client = new WebClient())
{
byte[] response =
client.UploadValues("http://dork.com/service", new NameValueCollection()
{
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
string result = System.Text.Encoding.UTF8.GetString(response);
}
您将需要这些包括:
using System;
using System.Collections.Specialized;
using System.Net;
如果您坚持使用静态方法/类:
public static class Http
{
public static byte[] Post(string uri, NameValueCollection pairs)
{
byte[] response = null;
using (WebClient client = new WebClient())
{
response = client.UploadValues(uri, pairs);
}
return response;
}
}
然后简单:
var response = Http.Post("http://dork.com/service", new NameValueCollection() {
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});