第一种:使用HttpWebRequest
string result = ""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl); request.Method = "POST"; request.ContentType = "application/json"; string data = "{ "header": { "token": "30xxx6aaxxx93ac8cxx8668xx39xxxx", "username": "jdads", "password": "liuqiangdong2010", "action": "" }, "body": {} }"; data = jsonData; byte[] byteData = Encoding.UTF8.GetBytes(data.ToString()); request.ContentLength = byteData.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); Console.WriteLine(result); } }
第二种:WebClient,也过时了:
第三种:HttpClient 当前主流用法,异步请求,自.NET4.5开始可从Nuget包管理中获取。
static async Task<Product> GetProductAsync(string path) { Product product = null; HttpResponseMessage response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { product = await response.Content.ReadAsAsync<Product>(); } return product; }
第四种:第三方类库:
RestSharp
REST API请求测试类库,可通过 NuGet 获得。
Flurl.Http
最新的便捷的api测试工具,使用HttpClient实现,可通过 NuGet 安装。
参考