Proper usage and error handling for HttpWebRequest and HttpWebResponse C#

HttpWebRequest webRequest = WebRequest.CreateHttp(new Uri("http://localhost", UriKind.Absolute));
webRequest.Method = "POST";

var requestBytes = Encoding.UTF8.GetBytes("content");

try
{
using (var requestStream = webRequest.GetRequestStream())
{
requestStream.Write(requestBytes, 0, requestBytes.Length);
}

using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))
{
var resp = reader.ReadToEnd();

// do something
}
}
catch (Exception e)
{
Log.Error(e.Message, e);

if (e is WebException)
{
var webException = (WebException)e;
var response = (HttpWebResponse)webException.Response;

if (response != null)
{
var message = new StreamReader(response.GetResponseStream()).ReadToEnd();

Log.Error(message);
}
else
{
Log.Error("Status code: " + webException.Status.ToString());
}
}
}

No Comments

Add a Comment