第一种:使用HttpWebRequest

string result = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);
            request.Method = "POST";
            request.ContentType = "application/json";
            string data = "{\n\"header\": {\n\"token\": \"30xxx6aaxxx93ac8cxx8668xx39xxxx\",\n\"username\": \"jdads\",\n\"password\": \"liuqiangdong2010\",\n\"action\": \"\"\n},\n\"body\": {}\n}";
            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 安装。

 

参考

Call a Web API From a .NET Client (C#)

相关文章:

  • 2021-11-30
  • 2021-10-02
  • 2021-09-07
  • 2021-08-29
  • 2021-08-04
猜你喜欢
  • 2022-02-14
  • 2021-06-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案