c# - 为什么我的 WebClient 无法读取失败的 API 调用?
问题描述
我的代码(用于使用 API 调用搜索蒸汽市场项目)应该将 API 调用的响应读取到我的程序中,这很好用,但是,当 API 调用失败时,我想显示一个单独的错误消息,让用户知道出了点问题,但目前它只会使代码崩溃。
成功的 API 调用示例如下:
这导致以下结果;
{"success":true,"lowest_price":"\u00a31.39","volume":"22","median_price":"\u00a31.40"}
到目前为止,这工作得很好,当使用不正确的链接时会出现问题,如下所示:
这会导致这样的错误;
{"success":false}
我想知道这种情况何时发生,以便我可以向用户显示一条消息,但是在我的代码的当前状态下,当它返回时它只会崩溃。这是我当前的代码:
webpage = "https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=" + Model.category + Model.weapon + " | " + Model.skin + " (" + Model.wear + ")";
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
if (webData.Substring(11, 1) == "t")
{
int lowestPos = webData.IndexOf("\"lowest_price\":\"");
int volumePos = webData.IndexOf("\",\"volume\":\"");
int medianPos = webData.IndexOf("\",\"median_price\":\"");
int endPos = webData.IndexOf("\"}");
Model.lowestPrice = webData.Substring(lowestPos + 16, volumePos - lowestPos - 16);
if (Model.lowestPrice.IndexOf("\\u00a3") != -1)
{
Model.lowestPrice = "£" + Model.lowestPrice.Substring(6);
}
Model.medianPrice = webData.Substring(medianPos + 18, endPos - medianPos - 18);
if (Model.medianPrice.IndexOf("\\u00a3") != -1)
{
Model.medianPrice = "£" + Model.medianPrice.Substring(6);
}
Model.volume = webData.Substring(volumePos + 12, medianPos - volumePos - 12);
}
else
{
Console.WriteLine("An error has occurred, please enter a correct skin");
}
错误发生在byte[] raw = wc.DownloadData(webpage);
任何帮助,将不胜感激 :)
解决方案
Webclient已弃用,如果可能,您应该考虑使用HttpClient 。Webclient 抛出异常。因此,您应该将代码包装在 try/catch 块中以捕获异常并做出相应的反应:
try
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
}
catch(System.Net.WebException e)
{
//handle the error here
}
推荐阅读
- arrays - 如何在 Unity3d 检查器中显示锯齿状数组?
- java - 复选框在带有动画的android中不起作用
- javascript - 从 html 中获取一个值并使用 javascript 更新 DOM
- mocking - 使用 axios 拦截器模拟 axios
- gtfs - 如何在 GTFS 数据中为每次旅行具有多个形状的路线构建折线
- github - 是否可以在 GitHub Actions 中的 Actions 之间保留 WORKDIR?
- xamarin.forms - 当控件获得焦点时更改 XamarinForms 条目的 TextColor
- json - 为什么使用 Postman 使用 JSON 调用 Express 时 req.body 总是为空?
- powershell - 从传递参数的 vbs 调用 power shell 脚本时出错
- x11 - XKeysymToKeycode 和键盘布局