首页 > 解决方案 > 为什么我的 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);

任何帮助,将不胜感激 :)

标签: c#webclient

解决方案


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
}

推荐阅读