使用 WebClient 和 C#,即使响应是 (400) 错误请求,我如何获取返回的数据? [英] Using a WebClient and C#, how do I get returned data even when the response is (400) Bad Request?
问题描述
我正在使用 Google Translate API 并尝试捕获在我收到 错误.(仅供参考:我知道 API 密钥是错误的,我只是在测试这个).
I am using the Google Translate API and am trying to capture the data returned when I get an error. (FYI: I know the API Key is wrong, I am just testing this).
问题在于,正如您通过单击链接所看到的那样,浏览器会显示错误信息,但 C# 会引发 WebException 并且我似乎无法获取响应数据.
The issue is that the browser, as you can see by clicking the link, displays the error info, but C# throws a WebException and I can't seem to get the response data.
这是我的代码:
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
之外,我是否需要使用不同的类?
How do I get the JSON error returned even when the response is a (400) Bad Request (or any other error resonse for that matter)? Do I need to use different classes other than a WebClient
?
推荐答案
这可能对你有帮助
catch ( WebException exception )
{
string responseText;
using(var reader = new StreamReader(exception.Response.GetResponseStream()))
{
responseText = reader.ReadToEnd();
}
}
这将为您提供 json 文本,然后您可以使用您喜欢的任何方法从 JSON 转换.
That will get you the json text, that you can then convert from JSON using whichever method you prefer.
这篇关于使用 WebClient 和 C#,即使响应是 (400) 错误请求,我如何获取返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!