Detailed explanation of the HTTP POST request method that contains body data in.NET
This article introduces several methods to send HTTP POST requests in .NET and pass body data.
1. HttpClient (recommended)
HttpClient is the preferred HTTP request method for .NET Core and later versions of .NET Framework. It provides asynchronous and high-performance operations.
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. Third-party library
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 (not recommended for new projects)
]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 (not recommended for new projects)
]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"); }
This article compares various methods of sending HTTP POST requests by .NET and recommends using HttpClient. For new projects, it is highly recommended to use HttpClient as it is more modern, performs better, and supports asynchronous operations.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3