

这里引入微软官方提供的HttpClient类来实现我们的目的。
首先,介绍一下官方HttpClient类的内容。
HttpClient 类
定义
命名空间:
System.Net.Http
程序集:
System.Net.Http.dll
Source:
HttpClient.cs
提供一个类,用于从 URI 标识的资源发送 HTTP 请求和接收 HTTP 响应。
public class HttpClient : System.Net.Http.HttpMessageInvoker
继承
Object - > HttpMessageInvoker - > HttpClient
示例:
// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();
static async Task Main()
{
// Call asynchronous network methods in a try/catch block to handle exceptions.
try
{
using HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method below
// string responseBody = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
构造函数
| 函数 | 描述 |
|---|---|
| HttpClient() | 使用释放此实例时释放的 HttpClientHandler 初始化 HttpClient 类的新实例。 |
| HttpClient(HttpMessageHandler) | 使用指定的处理程序初始化 HttpClient 类的新实例。 处理程序在释放此实例时被释放。 |
| HttpClient(HttpMessageHandler, Boolean) | 使用提供的处理程序初始化 HttpClient 类的新实例,并指定在释放此实例时是否应释放 |

最低0.47元/天 解锁文章
806

被折叠的 条评论
为什么被折叠?



