.NET platform sends a variety of methods to send HTTP post requests detailed
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
// 初始化 private static readonly HttpClient client = new HttpClient(); // POST 请求 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();
RESTSHARP is a popular third -party HTTP request library that provides convenient and easy -to -use APIs and rich functions.
// POST 请求 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; // 原始字符串内容
Flurl.http is a newer library, with smooth API and portable.
Method 3: httpwebrequest
// POST 请求 var responseString = await "http://www.example.com/recepticle.aspx" .PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" }) .ReceiveString();
<一> 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
// POST 请求 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();
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!