如何发出 HTTP POST 网络请求 [英] How to make an HTTP POST web request

查看:33
本文介绍了如何发出 HTTP POST 网络请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

规范
如何使用 POST 方法发出 HTTP 请求并发送一些数据?

我可以执行 GET 请求,但我不知道如何发出 POST 请求.

I can do a GET request, but I have no idea of how to make a POST request.

推荐答案

有几种方法可以执行 HTTP GETPOST 请求:

There are several ways to perform HTTP GET and POST requests:

适用于:.NET Framework 4.5+.NET Standard 1.1+.NET Core 1.0+ .

这是目前首选的方法,并且是异步和高性能的.大多数情况下使用内置版本,但对于非常旧的平台,有一个 NuGet 包.

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

设置

建议实例化一个HttpClient 在您的应用程序的生命周期内共享它,除非您有特定的理由不这样做.

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

参见 HttpClientFactory 用于 依赖注入解决方案.

  • POST

var values = new Dictionary<string, string>
{
    { "thing1", "hello" },
    { "thing2", "world" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

var responseString = await response.Content.ReadAsStringAsync();

  • GET

    var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
    

  • RestSharp

    • POST

     var client = new RestClient("http://example.com");
     // client.Authenticator = new HttpBasicAuthenticator(username, password);
     var request = new RestRequest("resource/{id}");
     request.AddParameter("thing1", "Hello");
     request.AddParameter("thing2", "world");
     request.AddHeader("header", "value");
     request.AddFile("file", path);
     var response = client.Post(request);
     var content = response.Content; // Raw content as string
     var response2 = client.Post<Person>(request);
     var name = response2.Data.Name;
    

    Flurl.Http

    它是一个较新的库,具有流畅的 API、测试助手、在后台使用 HttpClient 并且是可移植的.它可以通过 NuGet 获得.

    It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.

        using Flurl.Http;
    

    <小时>

    • POST

      var responseString = await "http://www.example.com/recepticle.aspx"
          .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
          .ReceiveString();
      

    • GET

      var responseString = await "http://www.example.com/recepticle.aspx"
          .GetStringAsync();
      

    • 适用于:.NET Framework 1.1+.NET Standard 2.0+.NET Core 1.0+.在 .NET Core 中,它主要是为了兼容性——它封装了 HttpClient,性能较低,并且不会获得新功能.

      Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

      using System.Net;
      using System.Text;  // For class Encoding
      using System.IO;    // For StreamReader
      

      <小时>

      • POST

        var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
        
        var postData = "thing1=" + Uri.EscapeDataString("hello");
            postData += "&thing2=" + Uri.EscapeDataString("world");
        var data = Encoding.ASCII.GetBytes(postData);
        
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = data.Length;
        
        using (var stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        
        var response = (HttpWebResponse)request.GetResponse();
        
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        

      • GET

        var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
        
        var response = (HttpWebResponse)request.GetResponse();
        
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        

      • 这是对 HttpWebRequest 的封装.HttpClient比较.

        This is a wrapper around HttpWebRequest. Compare with HttpClient.

        适用于:.NET Framework 1.1+NET Standard 2.0+.NET Core 2.0+

        using System.Net;
        using System.Collections.Specialized;
        

        <小时>

        • POST

          using (var client = new WebClient())
          {
              var values = new NameValueCollection();
              values["thing1"] = "hello";
              values["thing2"] = "world";
          
              var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
          
              var responseString = Encoding.Default.GetString(response);
          }
          

        • GET

          using (var client = new WebClient())
          {
              var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
          }
          

        • 这篇关于如何发出 HTTP POST 网络请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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