I’m using the following code to simulate a page post. (I’m subclassing WebClient so that I can extend some protected members.)
public class AuthorizeNetClient : WebClient
{
public string PostData(string url, FormCollection formData)
{
byte[] response = UploadValues(url, formData);
return Encoding.ASCII.GetString(response);
}
}
This code is straight forward, but I have two issues:
-
I know I will get an exception if there’s an error, but I think results with non-success HTTP status codes are still possible. Is there a way to get those status codes without needing to parse the results?
-
Also, I’m going to need to add a bunch of headers to make this seem like a real page post. Any good examples of doing this and the type of headers I need to add?
The only request header needed for a FORM POST is ‘content-type: x-www-form-urlencoded’.
Also, WebClient will throw an exception for all HTTP status codes != 2xx (ie. success) so you should be ok here. You just need to catch the WebException and see if the e.Status == WebExceptionStatus.ProtocolError. If that is the case, you can get the HttpWebResponse object from the Exception object ( e.Response ) and do whatever you want with it.