I have a Powershell script that uses System.Net.HttpWebRequest to communicate with a remote host.
I create the request, set properties accordingly and call getresponse() and getresponsestream() to read the entire response from the server to a string. This works fine as long as the server responds with a “200 OK” message.
If the server responds with a “400 Bad Request” or any other error code, getresponse() and getresponsestream() throw exceptions and return nothing. My problem is there is more detailed error information included in the response header which I need so I can do my own error handling.
How would I be able to retrieve this 400 Bad Request signal?
Edit: I misunderstood the question at first, but it turns out that you can retrieve the response header by using the
HttpWebResponse.GetResponseHeader()method. If an exception occurs, theHttpWebRequest.GetResponse()method returns$null, and you have to use this code to retrieve the HttpWebResponse object, so that you can callGetResponseHeader()on it:I’m pretty sure you’ll want to stick with the
System.Net.HttpWebRequestinstead of theSystem.Net.WebClientobject. Here is an example, similar to what you probably already have:The GetResponse() method returns a
HttpWebResponseobject, which has a property namedStatusCode, which points to a value in theHttpStatusCode.NET enumeration. Once you get a reference to the enumeration, we use thevalue__property to get the integer that is associated with the returned enum value.If you get a null value from the
GetResponse()method, then you’ll want to read the most current error message in your catch {..} block. TheException.ErrorRecordproperty should be the most helpful.http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx