小编典典

.NET: Simplest way to send POST with data and read response

all

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


阅读 61

收藏
2022-08-02

共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" }
});
2022-08-02