令我惊讶的是,在.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
上的Post
方法返回响应。
既然我们没有这么简单的东西,那么下一个最好的解决方案是什么?
如何发送包含数据的HTTP POST并获取响应的内容?
发布于 2010-11-03 23:28:30
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" }
});
发布于 2013-02-28 15:16:00
使用HttpClient:就Windows8应用程序开发而言,我遇到了这个问题。
var client = new HttpClient();
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("pqpUserName", "admin"),
new KeyValuePair<string, string>("password", "test@123")
};
var content = new FormUrlEncodedContent(pairs);
var response = client.PostAsync("youruri", content).Result;
if (response.IsSuccessStatusCode)
{
}
发布于 2010-11-03 23:25:28
使用WebRequest。来自Scott Hanselman
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
https://stackoverflow.com/questions/4088625
复制相似问题