“HttpClient”错误消息
本文关键字:消息 错误 HttpClient | 更新日期: 2023-09-27 18:14:11
我使用HttpClient
从服务器的API
获取响应。
这个API
类似于:
/api/图片/{0}
其中{0}
为图像名称。
像{"green", "red", "blue"}
我不知道当前存在哪些图像,所以我对所有三个图像进行API
调用:
- /api/图片/绿色
- /api/图片/红色
- /api/图片/蓝色
HttpClient
可能会返回许多错误消息,但是我想为
响应状态码不显示成功:404 (not Found).
问题:是否有可能使HttpClient
返回(在这种情况下)错误消息与404
?
HttpResponseMessage
类包含StatusCode
属性,那么为什么不像这样处理它呢?
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
switch (response.StatusCode)
{
case System.Net.HttpStatusCode.NotFound: { /* return here anything you want on 404 */ } break;
default: { /* default behavior */ } break;
}
}
响应对象将有一个StatusCode属性,可以通过以下方式访问:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
if (response.StatusCode != HttpStatusCode.OK)
...