适用范围:.NET Framework 4.5+、.NET Standard 1.1+ 和 .NET Core 1.0+。
设置:建议在应用程序的生命周期内实例化一个 HttpClient 并共享它。
1 2 3
using System.Net.Http;
privatestaticreadonly HttpClient client = new HttpClient();
POST请求示例
1 2 3 4 5 6 7 8 9
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();
方法B:第三方库
RestSharp
1 2 3 4 5 6 7 8 9
var client = new RestClient("http://example.com"); // client.Authenticator = new HttpBasicAuthenticator(username, password); var request = new RestRequest("resource/{id}"); request.AddParameter("thing1", "Hello"); request.AddParameter("thing2", "world"); request.AddHeader("header", "value"); request.AddFile("file", path); var response = client.Post(request); var content = response.Content; // Raw content as string
using System.Net; using System.Text; // For class Encoding using System.IO; // For StreamReader
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 = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
方法D:WebClient(不推荐用于新开发)
1 2 3 4 5 6 7 8 9 10 11 12
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); var responseString = Encoding.Default.GetString(response); }
核心代码
通用的HttpClient POST请求
1 2 3 4 5 6 7 8 9 10 11 12 13
using System.Net.Http;
privatestaticreadonly HttpClient client = new HttpClient();
var values = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } };
var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("http://example.com/api", content); var responseString = await response.Content.ReadAsStringAsync();