C#使用HttpClient异步HTTP请求

丌官运珧
2023-12-01

C#使用HttpClient异步HTTP请求,可以设置代理、header、编码,查看响应信息。

using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static async Task Main(string[] args)
        {
			// 注册加载编码
			System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
			// 代理
			var handler = new SocketsHttpHandler() { UseProxy = true, Proxy = new WebProxy("127.0.0.1", 10811), UseCookies = false, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };

			using (var client = new HttpClient(handler))
			{
				// 设置header信息
				client.Timeout = TimeSpan.FromSeconds(5);
				client.DefaultRequestHeaders.Host = "www.baidu.com";
				client.DefaultRequestHeaders.Referrer = new Uri("https://www.baidu.com/");
				client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");

				// 解决乱码问题
				byte[] rspBytes = await client.GetByteArrayAsync("https://www.baidu.com");
				var bb = Encoding.GetEncoding("GB2312").GetString(rspBytes);
				Console.WriteLine(bb);

				// 响应
				string rspText = await client.GetStringAsync("https://www.baidu.com");
				Console.WriteLine(rspText);

				// 响应状态
				HttpRequestMessage reqMsg = new HttpRequestMessage(HttpMethod.Get, "https://www.baidu.com");
				HttpResponseMessage rspMsg = await client.SendAsync(reqMsg);
				if (rspMsg.IsSuccessStatusCode)
				{
					string rspText1 = await rspMsg.Content.ReadAsStringAsync();
					Console.WriteLine(rspText1);
				}
			}
			Console.ReadKey();
		}
    }
}

转换工具

https://curlconverter.com/csharp/
https://github.com/curlconverter/curlconverter

参考

https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-7.0

 类似资料: