[C#] 纯文本查看 复制代码 using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
/*
* 文档地址:https://learn.microsoft.com/zh-cn/dotnet/api/system.net.http.httpclient?view=netframework-4.8
HttpClient 旨在实例化一次,并在应用程序的整个生命周期内重复使用。
在 .NET Core 和 .NET 5+ 中,HttpClient 将连接池在处理程序实例内,并在多个请求之间重复使用连接。
如果为每个请求实例化 HttpClient 类,则重负载下可用的套接字数将耗尽。 这种耗尽将导致 SocketException 错误。
-----HttpClient这个是官方文档推荐使用的----- 这个类会自动解码,解压数据
---还有WebRequest(已弃用)和HttpWebRequest
*/
namespace HttpClientDemo1 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private static HttpClientHandler _HttpHandler = new HttpClientHandler() {
CookieContainer = new CookieContainer()
};
private static HttpClient _HttpClient = new HttpClient(_HttpHandler);
//异步获取返回的字符串
private async void buttonGetString_Click(object sender, EventArgs e) {
Uri url = new Uri("https://www.baidu.com");
string baidu = await _HttpClient.GetStringAsync(url); //异步获取请求的字符串
textBox1.AppendText(baidu.Substring(0, 10));//截取前10个字符串
Console.WriteLine(baidu.Length);
//遍历cookies
foreach (Cookie cook in _HttpHandler.CookieContainer.GetCookies(url)) {
Console.WriteLine(cook.Name + ":" + cook.Value);
textBox1.AppendText(cook.Name + ":" + cook.Value);
}
}
//以任务的方式异步请求
private async void buttonSendAsync_Click(object sender, EventArgs e) {
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri("https://www.baidu.com");
// httpRequest.Content = new StringContent(""); //post提交时需要设置的数据,3种选择其中一个
//httpRequest.Content = new StreamContent();
// httpRequest.Content = new ByteArrayContent();
httpRequest.Headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
HttpResponseMessage httpResponse = await _HttpClient.SendAsync(httpRequest); //异步获取请求的HttpResponseMessage响应
//遍历协议头
foreach (var Headers in httpResponse.Headers) {
foreach (var Header in Headers.Value) {
Console.WriteLine(Headers.Key + ":" + Header);
}
}
Console.WriteLine("\r\n-----------------------------------------");
//遍历cookies
foreach (Cookie cook in _HttpHandler.CookieContainer.GetCookies(new Uri("https://www.baidu.com"))) {
Console.WriteLine(cook.Name + ":" + cook.Value);
textBox1.AppendText(cook.Name + ":" + cook.Value);
}
}
//异步请求,可以取消任务
private async void buttonSendAsyncCancelToken_Click(object sender, EventArgs e) {
CancellationTokenSource tokenSource = new CancellationTokenSource(); //创建一个令牌
tokenSource.CancelAfter(10); //10毫秒之后取消这个任务;
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri("https://www.baidu.com");
httpRequest.Headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
Task<HttpResponseMessage> httpResponseTask = _HttpClient.SendAsync(httpRequest, tokenSource.Token); //异步获取请求的HttpResponseMessage响应
try {
HttpResponseMessage httpResponse = await httpResponseTask;
foreach (var Headers in httpResponseTask.Result.Headers) {
foreach (var Header in Headers.Value) {
Console.WriteLine(Headers.Key + ":" + Header);
}
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}
|