.NET 中发送包含正文数据的 HTTP POST 请求方法详解
本文介绍在 .NET 中发送 HTTP POST 请求并传递正文数据的几种方法。
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