-->

Using a WebClient and C#, how do I get returned da

2020-06-12 02:45发布

问题:

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.