【WPF】04 Http消息处理类

在这里插入图片描述

在这里插入图片描述

这里引入微软官方提供的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 类的新实例,并指定在释放此实例时是否应释放
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值