C# HttpClient的使用方法总结

C# HttpClient的使用方法总结,直接上代码:

using System;
using System.IO;
using System.Net.Http;

namespace ConsoleApp1
{
    class Program
    {
        private static HttpClient client = new HttpClient();

        static void Main(string[] args)
        {
            client.BaseAddress = new Uri("http://localhost:8000");
            TestGet();
            TestPostByFormData();
            TestPostByJson();
            TestDownloadFile();
            TestUploadFile();
            Console.ReadLine();
        }

        /// <summary>
        /// Get请求
        /// </summary>
        static async void TestGet()
        {
            var res = await client.GetAsync("/Test/GetPerson");
            res.EnsureSuccessStatusCode();
            var rst = await res.Content.ReadAsStringAsync();
            Console.WriteLine(rst);
        }

        /// <summary>
        /// FormData形式的Post请求
        /// </summary>
        static async void TestPostByFormData()
        {
            var content = new MultipartFormDataContent();
            content.Add(new StringContent("张三"), "name");
            var res = await client.PostAsync("/Test/UpdateName", content);
            res.EnsureSuccessStatusCode();
            var rst = await res.Content.ReadAsStringAsync();
            Console.WriteLine(rst);
        }

        /// <summary>
        /// Json形式的Post请求
        /// </summary>
        static async void TestPostByJson()
        {
            var json =
@"{
  ""name"": ""李四"",
  ""mobileNumber"": ""13122233445"",
  ""address"": ""中山路""
}";
            var content = new StringContent(json);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var res = await client.PostAsync("/Test/UpdatePerson", content);
            res.EnsureSuccessStatusCode();
            var rst = await res.Content.ReadAsStringAsync();
            Console.WriteLine(rst);
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        static async void TestDownloadFile()
        {
            var res = await client.GetAsync("/Test/DownloadFile");
            res.EnsureSuccessStatusCode();
            var bytes = await res.Content.ReadAsByteArrayAsync();
            File.WriteAllBytes("D:\\test.jpg", bytes);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        static async void TestUploadFile()
        {
            var filePath = "D:\\test.png";
            var fileName = Path.GetFileName(filePath);
            var content = new MultipartFormDataContent();
            var bytes = File.ReadAllBytes(filePath);
            content.Add(new ByteArrayContent(bytes), "file", fileName);
            var res = await client.PostAsync("/Test/UploadFile", content);
            res.EnsureSuccessStatusCode();
            var rst = await res.Content.ReadAsStringAsync();
            Console.WriteLine(rst);
        }
    }
}

 

posted @ 2022-07-26 16:42  广阔之海  阅读(2603)  评论(0编辑  收藏  举报