当前位置: 首页 > web >正文

.Net HttpClient 处理响应数据

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>>();//result.Display();Console.WriteLine($"响应正常:内容为 {result}");
}//确保正确响应:异常
{try {var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=c");//确保异常response.EnsureSuccessStatusCode();//result.Display();var result = await response.Content.ReadFromJsonAsync<BaseResult<Account>>();Console.WriteLine($"响应正常:内容为 {result}");}catch(Exception e){Console.WriteLine($"请求异常:{e.Message}");} 
}//使用 ry catch 捕获所有异常
{try {var result = await SharedClient.GetFromJsonAsync<BaseResult<Account>>("api/Normal/GetAccount?id=a");//result.Display();Console.WriteLine($"响应正常:内容为 {result}");}catch(Exception e){Console.WriteLine($"请求异常:{e.Message}");}finally{//收发业务}
}

3、处理异常响应

3.1 try catch

//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;}//处理异常:也可以结合AOP,进行统一拦截处理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库(重试、降级、熔断等,可结合类型化客户端和工厂模式)

//Polly进行异常处理
var services = new ServiceCollection();
services.AddHttpClient(string.Empty)//配置默认命名客户端.ConfigureHttpClient(client => {client.BaseAddress = new Uri(webApiBaseUrl);})//设置Policy错误处理快捷扩展方法.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 接收响应体数据

//响应体数据(json为例)
{var response = await SharedClient.GetAsync("api/Normal/GetAccount?id=1");//获取响应体内容var content = await response.Content.ReadAsStringAsync();Console.WriteLine($"响应体数据:{content}"); 
}
http://www.xdnf.cn/news/5460.html

相关文章:

  • 每日一题洛谷P8615 [蓝桥杯 2014 国 C] 拼接平方数c++
  • 被一个人影响情绪是爱吗?这 3 个真相越早明白越好
  • AI面经总结-试读
  • 深度解析六大AI爬虫工具:crawl4ai、FireCrawl、Scrapegraph-ai、Jina、SearXNG、Tavily技术对比与实战指南
  • COT思维链:SequentialChain 方法有哪些参数;优化后的提示词
  • ES面试题系列「一」
  • MySQL的索引分类
  • 软件体系结构(Software Architecture)
  • IDEA:如何设置最上面菜单栏一直显示出来
  • 图片转ICO图标工具
  • 一个网球新手的学习心得
  • 单链表设计与实现
  • 锁相放大技术:从噪声中提取微弱信号的利器
  • C PRIMER PLUS——第9节:动态内存分配、存储类别、链接和内存管理
  • 程序中的内存从哪里来?
  • arctan x 导数推理
  • Java 1.8(也称为Java 8)
  • 4.4 os模块
  • MySql事务索引
  • 图灵奖获得者经典论文系列(1969):迈向人工智能的步伐(马文·明斯基)
  • 2023 河南ccpc
  • Python与矢量网络分析仪3671E:通道插损自动化校准(Vscode)
  • AI(学习笔记第三课) 使用langchain进行AI开发(2)
  • VSCode1.101.0便携版|中英文|编辑器|安装教程
  • 大模型项目:普通蓝牙音响接入DeepSeek,解锁语音交互新玩法
  • 【React中useRef钩子详解】
  • 《AI大模型应知应会100篇》第56篇:LangChain快速入门与应用示例
  • 【Leetcode 每日一题】1550. 存在连续三个奇数的数组
  • 【心海资源】【最新话费盗u】【未测】提币对方官方波场+没有任何加密+无后门+前端VUE
  • 元数据分类