Reference:. Net httpwebrequest.getresponse () raises exception when HTTP status code (Bad request) is returned
C # code
Using System;
Using System.IO;
Using System.Net;
public class Test
{
static void Main ()
{
HttpWebRequest request = (HttpWebRequest) webrequest.create ("HTTP://CSHARPINDEPTH.COM/ASD");
Try
{
using (Stream data = Request. GetResponse (). GetResponseStream ())
{
using (StreamReader reader = new StreamReader (data))
{
string text = Reader. ReadToEnd ();
Console.WriteLine (text);
}
}
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse) ex.response;
Console.WriteLine ("Error code: {0}", Response. StatusCode);
if (response. StatusCode = = httpstatuscode.badrequest)
{
using (Stream data = response. GetResponseStream ())
{
using (StreamReader reader = new StreamReader (data))
{
string text = Reader. ReadToEnd ();
Console.WriteLine (text);
}
}
}
}
}
}
HttpWebRequest.GetResponse () raises exception when HTTP status code [Bad Request] is returned