令我惊讶的是,在.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,并在静态类Post
上返回Http
方法的响应。
既然我们没有这么简单,那么下一个最佳解决方案是什么?
如何发送带有数据的HTTP POST并获取响应的内容?
答案 0 :(得分:285)
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" }
});
答案 1 :(得分:73)
使用HttpClient:就Windows 8应用程序开发问题而言,我遇到了这个问题。
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)
{
}
答案 2 :(得分:47)
使用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();
}
答案 3 :(得分:33)
private void PostForm()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dork.com/service");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData ="home=Cosby&favorite+flavor=flies";
byte[] bytes = Encoding.UTF8.GetBytes(postData);
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
stream.Dispose();
reader.Dispose();
}
答案 4 :(得分:12)
就个人而言,我认为执行http帖子并获得响应的最简单方法是使用WebClient类。这个类很好地抽象了细节。在MSDN文档中甚至还有一个完整的代码示例。
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
在您的情况下,您需要UploadData()方法。 (同样,代码示例包含在文档中)
http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx
UploadString()可能也会起作用,它会将它抽象出一个级别。
http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx
答案 5 :(得分:7)
我知道这是一个老线程,但希望它能帮到某个人。
public static void SetRequest(string mXml)
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp("http://dork.com/service");
webRequest.Method = "POST";
webRequest.Headers["SOURCE"] = "WinApp";
// Decide your encoding here
//webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentType = "text/xml; charset=utf-8";
// You should setContentLength
byte[] content = System.Text.Encoding.UTF8.GetBytes(mXml);
webRequest.ContentLength = content.Length;
var reqStream = await webRequest.GetRequestStreamAsync();
reqStream.Write(content, 0, content.Length);
var res = await httpRequest(webRequest);
}
答案 6 :(得分:5)
你可以使用类似这样的伪代码:
request = System.Net.HttpWebRequest.Create(your url)
request.Method = WebRequestMethods.Http.Post
writer = New System.IO.StreamWriter(request.GetRequestStream())
writer.Write("your data")
writer.Close()
response = request.GetResponse()
reader = New System.IO.StreamReader(response.GetResponseStream())
responseText = reader.ReadToEnd
答案 7 :(得分:3)
鉴于其他答案已有数年历史,目前我的想法可能会有所帮助:
最简单的方法
private async Task<string> PostAsync(Uri uri, HttpContent dataOut)
{
var client = new HttpClient();
var response = await client.PostAsync(uri, dataOut);
return await response.Content.ReadAsStringAsync();
// For non strings you can use other Content.ReadAs...() method variations
}
更实际的示例
通常,我们正在处理已知类型和JSON,因此您可以通过许多实现来进一步扩展该思想,例如:
public async Task<T> PostJsonAsync<T>(Uri uri, object dtoOut)
{
var content = new StringContent(JsonConvert.SerializeObject(dtoOut));
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
var results = await PostAsync(uri, content); // from previous block of code
return JsonConvert.DeserializeObject<T>(results); // using Newtonsoft.Json
}
如何称呼它的例子:
var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);