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

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

Patricia Arquette
發布: 2025-02-02 16:26:09
原創
243 人瀏覽過

.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<string, string>
{
    { "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,因為它更現代化,性能更高,並且支持異步操作。

以上是如何在.NET中使用正文數據發送HTTP POST請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板