.NET: 用数据和读取响应发送 POST 的最简单方法

令我惊讶的是,我不能做任何事情几乎这样简单,从我可以告诉,在。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"
);

上面这段假设的代码使用数据生成一个 HTTPPOST,并返回来自静态类 Http上的 Post方法的响应。

既然我们没有这么简单的东西,下一个最好的解决办法是什么?

如何发送带有数据的 HTTP POST 并获取响应的内容?

470592 次浏览

使用 WebRequest.From 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();
}

就我个人而言,我认为最简单的方法是使用 WebClient 类来完成 http 发布并获得响应。这个类很好地抽象了细节。甚至在 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

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();
}
   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" }
});

您可以使用下面这样的伪代码:

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

使用 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)
{




}

我知道这是一个老线索,但希望它能帮助某人。

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);
}

鉴于其他答案都是几年前的了,以下是我目前的一些想法,可能会有所帮助:

最简单的方法

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
}

An example of how this could be called:

var dataToSendOutToApi = new MyDtoOut();
var uri = new Uri("https://example.com");
var dataFromApi = await PostJsonAsync<MyDtoIn>(uri, dataToSendOutToApi);