Using a WebClient and C#, how do I get returned data even when the response is (400) Bad Request?

走远了吗. 提交于 2020-01-12 07:06:32

问题


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).

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.

Here is my code:

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;
}

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?


回答1:


This may help you

catch ( WebException exception )
{
   string responseText;

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

That will get you the json text, that you can then convert from JSON using whichever method you prefer.

Retrieved from: Get WebClient errors as string




回答2:


I would catch the specific exception you are receiving - it will have pertinent data concerning the failure.

According to MSDN, WebException.Response will contain the response received from the server.

Once you are able to retrieve the JSON data from this response object, then you'll need to deserialize it yourself if you want.



来源:https://stackoverflow.com/questions/15235308/using-a-webclient-and-c-how-do-i-get-returned-data-even-when-the-response-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!