首页 >后端开发 >C++ >如何在.NET中使用正文数据发送HTTP POST请求?

如何在.NET中使用正文数据发送HTTP POST请求?

Patricia Arquette
Patricia Arquette原创
2025-02-02 16:26:09205浏览

.NET 中发送包含正文数据的 HTTP POST 请求方法详解

本文介绍在 .NET 中发送 HTTP POST 请求并传递正文数据的几种方法。

How to Send HTTP POST Requests with Body Data in .NET?

1. HttpClient (推荐)

对于 .NET Core 和更新版本的 .NET Framework,HttpClient 是首选的 HTTP 请求方法。它提供异步和高性能操作。

<code class="language-csharp">using System.Net.Http;
var client = new HttpClient();
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);</code>

2. 第三方库

RestSharp:

<code class="language-csharp">using RestSharp;
var client = new RestClient("http://example.com");
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
var response = client.Post(request);</code>

Flurl.Http:

<code class="language-csharp">using Flurl.Http;
var responseString = await "http://www.example.com/recepticle.aspx"
    .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
    .ReceiveString();</code>

3. HttpWebRequest (不推荐用于新项目)

POST:

<code class="language-csharp">using System.Net;
using System.Text;
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);
using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); }
var response = request.GetResponse();</code>

GET:

<code class="language-csharp">var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = request.GetResponse();</code>

4. WebClient (不推荐用于新项目)

POST:

<code class="language-csharp">using System.Net;
using System.Collections.Specialized;
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);
}</code>

GET:

<code class="language-csharp">using (var client = new WebClient()) { var responseString = client.DownloadString("http://www.example.com/recepticle.aspx"); }</code>

本文比较了多种.NET发送HTTP POST请求的方法,并建议使用HttpClient。 对于新项目,强烈建议使用HttpClient,因为它更现代化,性能更高,并且支持异步操作。

以上是如何在.NET中使用正文数据发送HTTP POST请求?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn