为什么我的WebClient无法读取失败的API调用?

问题描述

我的代码(旨在使用API​​调用搜索蒸汽市场商品)应该将API调用的响应读取到我的程序中,并且效果很好,但是,当API调用失败时,我想显示一个单独的错误消息,使用户知道出了点问题,但当前只会使代码崩溃。

成功调用API的示例是:

https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=Glock-18%20%7C%20Steel%20Disruption%20%28Minimal%20Wear%29

结果如下;

{"success":true,"lowest_price":"\u00a31.39","volume":"22","median_price":"\u00a31.40"}

到目前为止,这一切都很好,当使用不正确的链接时会出现问题,如下所示:

https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=this-skin-does-not-exist

这样会导致错误

{"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
}