.NET:最简单的方法来发送POST数据和读取响应 [英] .NET: Simplest way to send POST with data and read response
本文介绍了.NET:最简单的方法来发送POST数据和读取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
要我惊讶的是,我不能做任何事情几乎一样简单,这一点,从我可以告诉,在.NET基础类库:
字节[]响应= Http.Post
(
网址:http://dork.com/service
的contentType:应用程序/ x-WWW的形式urlen codeD,
CONTENTLENGTH:32,
内容:家=寇斯比&功放;最喜欢的+香精=苍蝇
);
此假设code以上,使一个HTTP POST,用数据,并返回一个发布
方法的静态类的响应的Http
。
由于我们没有离开这个东西很容易,什么是下一个最好的解决方案?
如何发送一个HTTP POST数据,并得到回应的内容?
解决方案
使用(Web客户端的客户端=新的Web客户端())
{
byte []的响应=
client.UploadValues(http://dork.com/service,新的NameValueCollection()
{
{家,天才老爹},
{最爱+香精,苍蝇}
});
字符串结果= System.Text.Encoding.UTF8.GetString(响应);
}
您将需要这些包括:
使用系统;
使用System.Collections.Specialized;
使用System.Net;
如果您坚持使用一个静态方法/类:
公共静态类的Http
{
公共静态byte []的帖子(字符串URI,NameValueCollection中对)
{
byte []的响应= NULL;
使用(Web客户端的客户端=新的Web客户端())
{
响应= client.UploadValues(URI,对);
}
返回响应;
}
}
然后简单:
VAR响应= Http.Post(http://dork.com/service,新的NameValueCollection(){
{家,天才老爹},
{最爱+香精,苍蝇}
});
To my surprise, I can't do anything nearly as simple as this, from what I can tell, in the .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"
);
This hypothetical code above makes an HTTP POST, with data, and returns the response from a Post
method on a static class Http
.
Since we're left without something this easy, what's the next best solution?
How do I send an HTTP POST with data AND get the response's content?
解决方案
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);
}
You will need these includes:
using System;
using System.Collections.Specialized;
using System.Net;
If you're insistent on using a static method/class:
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;
}
}
Then simply:
var response = Http.Post("http://dork.com/service", new NameValueCollection() {
{ "home", "Cosby" },
{ "favorite+flavor", "flies" }
});
这篇关于.NET:最简单的方法来发送POST数据和读取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文