HttpClient 处理响应数据
1、初始化及全局设置
#!import ./ini.ipynb
2、处理响应状态
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");if(response.StatusCode == System.Net.HttpStatusCode.OK){var content = await response.Content.ReadAsStringAsync();Console.WriteLine($"响应码正常:{content}");}
}
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=b");if(response.StatusCode != System.Net.HttpStatusCode.OK){Console.WriteLine($"响应码异常:状态码 {response.StatusCode}");}
}
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");response.EnsureSuccessStatusCode();var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();Console.WriteLine($"响应正常:内容为 {result}");
}
{try {var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=c");response.EnsureSuccessStatusCode();var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();Console.WriteLine($"响应正常:内容为 {result}");}catch(Exception e){Console.WriteLine($"请求异常:{e.Message}");}
}
{try {var result = await SharedClient.GetFromJsonAsync<BaseResult<Account>>("api/Normal/GetAccount?id=a");Console.WriteLine($"响应正常:内容为 {result}");}catch(Exception e){Console.WriteLine($"请求异常:{e.Message}");}finally{}
}
3、处理异常响应
3.1 try catch
{try {var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=c");response.EnsureSuccessStatusCode();var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();Console.WriteLine($"响应正常:内容为 {result}");}catch(Exception e){Console.WriteLine($"接口异常:{e.Message}");}finally{}
}
3.2 管道统一处理
public class ExceptionDelegatingHandler : DelegatingHandler
{protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken){Console.WriteLine("ExceptionDelegatingHandler -> Send -> Added Token");HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);try {response = base.Send(request, cancellationToken);response.EnsureSuccessStatusCode();}catch(Exception ex){Console.WriteLine($"中间件中,接口调用异常:{ex.Message}");}finally{Console.WriteLine("ExceptionDelegatingHandler -> Send -> After");}return response;}protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){Console.WriteLine("ExceptionDelegatingHandler -> SendAsync -> Before");HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);try {response = await base.SendAsync(request, cancellationToken);response.EnsureSuccessStatusCode();}catch(Exception ex){Console.WriteLine($"中间件中,接口调用异常:{ex.Message}");}finally{Console.WriteLine("ExceptionDelegatingHandler -> Send -> After");}return response;}
}
{ExceptionDelegatingHandler exceptionHandler = new ExceptionDelegatingHandler(){InnerHandler = new SocketsHttpHandler()};HttpClient clientWithExceptionHandler = new HttpClient(exceptionHandler){BaseAddress = new Uri(webApiBaseUrl),};var response = await clientWithExceptionHandler.GetAsync("api/Normal/GetAccount?id=c");if(response.StatusCode == System.Net.HttpStatusCode.OK){var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();Console.WriteLine($"响应正常:内容为 {result}");}else{Console.WriteLine($"接口异常:状态码 {response.StatusCode}");}
}
3.3 类型化客户端统一处理
public class HelloApiService
{public HttpClient Client { get; set; }public HelloApiService(HttpClient httpClient){Client = httpClient;}public async Task<string> Ping(){try {var content = await Client.GetStringAsync("/api/Hello/Ping2");return content;}catch(Exception ex){return $"远程调用异常:{ex.Message}";}}
}
{var services = new ServiceCollection();services.AddHttpClient<HelloApiService>(client => {client.BaseAddress = new Uri(webApiBaseUrl);}).ConfigureHttpClient(client=>{client.Timeout = TimeSpan.FromSeconds(1);});var apiService = services.BuildServiceProvider().GetService<HelloApiService>();var s = await apiService.Ping();Console.WriteLine(s);
}
3.4 Polly库(重试、降级、熔断等,可结合类型化客户端和工厂模式)
var services = new ServiceCollection();
services.AddHttpClient(string.Empty).ConfigureHttpClient(client => {client.BaseAddress = new Uri(webApiBaseUrl);}).AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]{TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(2),TimeSpan.FromSeconds(4),})).AddTransientHttpErrorPolicy(builder => builder.RetryAsync(1));var factory = services.BuildServiceProvider().GetService<IHttpClientFactory>();
var content = await factory.CreateClient().GetStringAsync("/api/polly8/RandomException");
Console.WriteLine($"响应内容:{content}");
4、处理响应数据
4.1 接收响应头数据
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");Console.WriteLine("响应头:");foreach(var header in response.Headers){var headerValues = string.Join(",", header.Value);Console.WriteLine($"{header.Key} = {headerValues}");}
}
4.2 接收响应体数据
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");var content = await response.Content.ReadAsStringAsync();Console.WriteLine($"响应体数据:{content}");
}