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

问题描述

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

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...