首頁 >後端開發 >C++ >如何在.NET中使用正文數據發送HTTP POST請求?

如何在.NET中使用正文數據發送HTTP POST請求?

Patricia Arquette
Patricia Arquette原創
2025-02-02 16:26:09240瀏覽

.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