跳到主要内容
版本:2.0

创建HttpClient

定义

命名空间:TouchSocket.Http
程序集:TouchSocket.Http.dll

一、说明

HttpClient是Http客户端类。主要用于请求Http报文。与.net的HttpClient不同的是,此处的HttpClient,是基于单个连接的客户端,且有明显的连接、断开连接等动作。

二、可配置项

继承TcpClient

三、支持插件接口

支持ITcpPlugin接口。

四、使用HttpClient

4.1 创建HttpClient

HttpClient client = new HttpClient();

client.Setup(new TouchSocketConfig()
.SetRemoteIPHost(new IPHost("http://localhost:7219")));
client.Connect();//先做连接

4.2 常规请求

HttpRequest request = new HttpRequest();
request
.InitHeaders()
.SetUrl("/WeatherForecast")
.SetHost(client.RemoteIPHost.Host)
.AsGet();

var respose = client.Request(request, millisecondsTimeout: 1000*10);
Console.WriteLine(respose.GetBody());

4.3 请求流数据

var request = new HttpRequest();
request.InitHeaders()
.SetUrl("/WeatherForecast")
.SetHost(client.RemoteIPHost.Host)
.AsGet();

var respose = client.Request(request, millisecondsTimeout: 1000 * 10);

var buffer = new byte[1024 * 64];
while (true)
{
int r = respose.Read(buffer, 0, buffer.Length);
if (r==0)
{
break;
}
Console.WriteLine(r);
}
Console.WriteLine(respose.GetBody());

五、创建HttpsClient

如果需要连接到Https服务器。则必须手动配置Ssl。示例如下:

如果服务器证书是由证书机构颁发,则只需填充TargetHostSslProtocols

SetClientSslOption(new ClientSslOption() { TargetHost = "localhost", SslProtocols = SslProtocols.Tls12 })

如果服务器证书是由自己制作的,则需要加载证书文件,和必要的验证

.SetClientSslOption(new ClientSslOption()
{
ClientCertificates = new X509CertificateCollection() { new X509Certificate2("RRQMSocket.pfx", "RRQMSocket") },
SslProtocols = SslProtocols.Tls12,
TargetHost = "127.0.0.1",
CertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; }
});

本文示例Demo