.net HttpClient使用
程序猿想成程序狮 人气:3创建一个名为HttpClientTest的Web API项目
新建Clients文件夹,用于存放自定义的HttpClient
在Clients下新建一个MyHttpClient类
代码为:
namespace HttpClientTest.Clients { public class MyHttpClient { private readonly HttpClient _client; public MyHttpClient(HttpClient client) { _client = client; } public async Task<string> ShowAsync() { return await _client.GetStringAsync("https://www.baidu.com"); } } }
将自定义的MyHttpClient服务注册进容器中
services.AddHttpClient<MyHttpClient>();
新建一个TestController来对我们的MyHttpClient做一个测试
using HttpClientTest.Clients; using Microsoft.AspNetCore.Mvc; namespace HttpClientTest.Controllers { [ApiController] [Route("[controller]/[action]")] public class TestController : ControllerBase { private readonly MyHttpClient _myHttpClient; public TestController(MyHttpClient myHttpClient) { _myHttpClient = myHttpClient; } [HttpGet] public async Task<object> GetAsync() { return await _myHttpClient.ShowAsync(); } } }
访问GetAsync接口,发现成功返回了百度首页的html内容
很多时候,我们希望通过相对路径的方式来对远程服务进行访问
可以把MyHttpClient改为:
namespace HttpClientTest.Clients { public class MyHttpClient { private readonly HttpClient _client; public MyHttpClient(HttpClient client) { _client = client; } public async Task<string> ShowAsync() { //return await _client.GetStringAsync("https://www.baidu.com"); return await _client.GetStringAsync("/"); } } }
在注册服务时就要配置基地址
services.AddHttpClient<MyHttpClient>(client => { client.BaseAddress = new Uri("https://www.baidu.com"); });
加载全部内容