Search code examples
c#webclienthttp-status-code-400

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


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?


Solution

  • 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