」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在.NET中使用正文數據發送HTTP POST請求?

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

發佈於2025-03-05
瀏覽:980

.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 請求方法。它提供異步和高性能操作。

using System.Net.Http;
var client = new HttpClient();
var values = new Dictionary
{
    { "thing1", "hello" },
    { "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);

2. 第三方庫

RestSharp:

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

Flurl.Http:

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

3. HttpWebRequest (不推薦用於新項目)

POST:

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

GET:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = request.GetResponse();

4. WebClient (不推薦用於新項目)

POST:

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

GET:

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

本文比較了多種.NET發送HTTP POST請求的方法,並建議使用HttpClient。 對於新項目,強烈建議使用HttpClient,因為它更現代化,性能更高,並且支持異步操作。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3