c#httpclient中get、 POST、PUT、DELETE、HEAD、OPTIONS、TRACE方法代码实现
时间: 2023-09-13 14:11:08 浏览: 177
1. GET方法
```csharp
using System.Net.Http;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 发送GET请求
HttpResponseMessage response = await client.GetAsync("http://www.example.com");
string responseBody = await response.Content.ReadAsStringAsync();
```
2. POST方法
```csharp
using System.Net.Http;
using System.Text;
using System.Text.Json;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 准备POST请求数据
var data = new { name = "John", age = 30 };
var jsonContent = JsonSerializer.Serialize(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 发送POST请求
HttpResponseMessage response = await client.PostAsync("http://www.example.com", content);
string responseBody = await response.Content.ReadAsStringAsync();
```
3. PUT方法
```csharp
using System.Net.Http;
using System.Text;
using System.Text.Json;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 准备PUT请求数据
var data = new { name = "John", age = 30 };
var jsonContent = JsonSerializer.Serialize(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 发送PUT请求
HttpResponseMessage response = await client.PutAsync("http://www.example.com", content);
string responseBody = await response.Content.ReadAsStringAsync();
```
4. DELETE方法
```csharp
using System.Net.Http;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 发送DELETE请求
HttpResponseMessage response = await client.DeleteAsync("http://www.example.com");
string responseBody = await response.Content.ReadAsStringAsync();
```
5. HEAD方法
```csharp
using System.Net.Http;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 发送HEAD请求
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, "http://www.example.com");
HttpResponseMessage response = await client.SendAsync(request);
```
6. OPTIONS方法
```csharp
using System.Net.Http;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 发送OPTIONS请求
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Options, "http://www.example.com");
HttpResponseMessage response = await client.SendAsync(request);
```
7. TRACE方法
```csharp
using System.Net.Http;
// 创建HttpClient对象
HttpClient client = new HttpClient();
// 发送TRACE请求
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Trace, "http://www.example.com");
HttpResponseMessage response = await client.SendAsync(request);
```
阅读全文