WebClient.DownloadString引发“ System.Net.WebException”

时间:2019-06-05 15:34:11

标签: c# html .net webclient

WebClient.DownloadString每次运行都会失败,并在System.dll中抛出“ System.Net.WebException”。调用方式有问题吗?下面的代码。

using (var wc = new WebClient())
            {
                wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
                try
                {
                    var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}", 
                            ConfigurationManager.AppSettings["which_api_url"], 
                            Uri.EscapeDataString(subjectName)));
                    return result;
                }
                catch(Exception ex)
                {
                    result.Status = ResultStatus.Failed;
                    return result;
                }
           }

1 个答案:

答案 0 :(得分:1)

WebException会给您错误。

using (var wc = new WebClient())
{
    wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
    try
    {
        var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}", 
                ConfigurationManager.AppSettings["which_api_url"], 
                Uri.EscapeDataString(subjectName)));
        return result;
    }
    catch(Exception ex)
    {
        WebException we = ex as WebException;
        if (we != null && we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            // it can be 404, 500 etc...
            Console.WriteLine(response.StatusCode);
        }
        result.Status = ResultStatus.Failed;
        return result;
    }
}