.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" ); 

上面这个假设的代码使用HTTP来发送数据,并从静态类HttpPost方法返回响应。

既然我们没有这么容易的事情,那么下一个最好的解决scheme是什么呢?

如何发送一个HTTP POST与数据并得到响应的内容?

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

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

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

就我个人而言,我认为做一个http post最简单的方法就是使用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

我知道这是一个古老的线索,但希望它有助于某个人。

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

你可以使用这样的伪代码:

 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