---
id: httpclient
title: 创建HttpClient
---

### 定义

命名空间：TouchSocket.Http <br/>
程序集：[TouchSocket.Http.dll](https://www.nuget.org/packages/TouchSocket.Http)

## 一、说明

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


## 二、可配置项

继承TcpClient

<a name="mMhq1"></a>

## 三、支持插件接口

支持**ITcpPlugin**接口。

<a name="LAsiE"></a>

## 四、使用HttpClient

### 4.1 创建HttpClient
```csharp showLineNumbers
HttpClient client = new HttpClient();

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

### 4.2 常规请求

```csharp showLineNumbers
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 请求流数据

```csharp showLineNumbers
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());
```

<a name="TixmX"></a>

## 五、创建HttpsClient

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

如果服务器证书是由**证书机构颁发**，则只需填充**TargetHost**和**SslProtocols**。

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

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

```csharp showLineNumbers
.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](https://gitee.com/RRQM_Home/TouchSocket/tree/master/examples/Http)