使用WebClient和C#,当响应为(400) Bad Request时,如何获取返回的数据?

12
我正在使用Google翻译API,并尝试捕获在获取错误时返回的数据。(FYI: 我知道API密钥是错误的,我只是在测试。)
问题是浏览器(通过单击链接可以看到)显示错误信息,但C#会抛出WebException,我似乎无法获取响应数据。
这是我的代码:
string url = "https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world";
WebClient clnt = new WebClient();

//Get string response
try
{
    strResponse = clnt.DownloadString(url);
    System.Diagnostics.Debug.Print(strResponse);
}
catch (Exception ex)
{
    System.Windows.Forms.MessageBox.Show(ex.Message);
    return null;
}

当响应为(400)错误请求(或任何其他错误响应)时,如何获取返回的JSON错误?我需要使用不同于WebClient的类吗?

2个回答

28

这可能会对你有所帮助

catch ( WebException exception )
{
   string responseText;

   using(var reader = new StreamReader(exception.Response.GetResponseStream()))
   {
     responseText = reader.ReadToEnd();
   }
}

这将为您获取JSON文本,然后您可以使用任何喜欢的方法将其从JSON转换。
从中检索:获取WebClient错误字符串

如果它不抛出异常,是否可能获得此对象? - DFTR

1
我会捕获您所接收到的特定异常 - 它将包含有关失败的相关数据。
根据 MSDN,WebException.Response 将包含从服务器接收到的响应。
一旦您能够从此响应对象检索JSON数据,那么如果您想要,就需要自己进行反序列化。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接