.NET:发送带有数据和读取响应的 POST 的最简单方法 [英] .NET: Simplest way to send POST with data and read response

查看:21
本文介绍了.NET:发送带有数据和读取响应的 POST 的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是,据我所知,在 .NET BCL 中,我几乎不能做任何像这样简单的事情:

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

上面的这个假设代码使用数据创建一个 HTTP POST,并从静态类 Http 上的 Post 方法返回响应.

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?

如何发送带有数据的 HTTP POST 并获取响应的内容?

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

您将需要这些包括:

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

那么简单:

var response = Http.Post("http://dork.com/service", new NameValueCollection() {
    { "home", "Cosby" },
    { "favorite+flavor", "flies" }
});

这篇关于.NET:发送带有数据和读取响应的 POST 的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆