Tuesday, October 21, 2014

Catch WebException from HttpWebRequest POST error response.

A WebException will be thrown if a non 200 status code is returned from the server.  To check the message returned, catch it and read the response.


try
{ 
  byte[] buf = Encoding.UTF8.GetBytes(payload);
  httpReq.ContentLength = buf.Length;
  httpReq.GetRequestStream().Write(buf, 0, buf.Length);
 
  HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();

   if (resp.StatusCode != HttpStatusCode.NoContent && resp.StatusCode != HttpStatusCode.NotFound)
  {   
    return resp.GetResponseStream(); //Successful response
  }
}

catch (WebException wex)
{ 
  using (var stream = ex.Response.GetResponseStream())

  using (var reader = new StreamReader(stream))
  {   

    Console.WriteLine(reader.ReadToEnd()); //Message returned from client
  }

}
catch (Exception ex)
{
    // Something more serious happened
    // like for example you don't have network access
    // we cannot talk about a server exception here as
    // the server probably was never reached

}
 

No comments: