小编典典

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

c#

令我惊讶的是,在.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并获取响应的内容?


阅读 279

收藏
2020-05-19

共1个答案

小编典典

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