.NET platform sends a variety of methods to send HTTP post requests detailed
This article will fully explain how to send HTTP post requests under the .NET framework. This is a common method for sending data to the server for processing.
Recommended method: httpclient
In the .NET, using the
class is the preferred method for sending HTTP requests. It provides a high -performance asynchronous way to send requests and receiving responses. HttpClient
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private static readonly HttpClient 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);
var responseString = await response.Content.ReadAsStringAsync();
|
Copy after login
Method 2: The third party library
RESTSHARP
RESTSHARP is a popular third -party HTTP request library that provides convenient and easy -to -use APIs and rich functions.
Flurl.http 1 2 3 4 5 6 7 | 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);
var content = response.Content;
|
Copy after login
Flurl.http is a newer library, with smooth API and portable.
Method 3: httpwebrequest
1 2 3 4 | var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync( new { thing1 = "hello" , thing2 = "world" })
.ReceiveString();
|
Copy after login
<> abandoned
<一> is an older method. It is not recommended for new projects, because its performance is low and the function is not as good as .
Method 4: Webclient HttpWebRequest
HttpClient
<> abandoned
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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);
request.Method = "POST" ;
request.ContentType = "application/x-www-form-urlencoded" ;
request.ContentLength = data.Length;
using ( var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
|
Copy after login
is a
packaging device, which is usually not recommended for new projects.
The above is the detailed content of How to Send HTTP POST Requests in .NET Using HttpClient, RestSharp, and Other Methods?. For more information, please follow other related articles on the PHP Chinese website!