I am using the WebClient
class to post some data to a web form. I would like to get the response status code of the form submission. So far I've found out how to get the status code if there is a exception
Catch wex As WebException If TypeOf wex.Response Is HttpWebResponse Then msgbox(DirectCast(wex.Response, HttpWebResponse).StatusCode) End If
However if the form is submitted successfully and no exception is thrown then I won't know the status code(200,301,302,...)
Is there some way to get the status code when there is no exceptions thrown?
PS: I prefer not to use httpwebrequest/httpwebresponse
If you're using WebClient to invoke an HTTP request, you can use the onStatus() method to handle a specific response status code.
NET 4.5 platform the community developed an alternative. Today, RestSharp is one of the only options for a portable, multi-platform, unencumbered, fully open-source HTTP client that you can use in all of your applications. It combines the control of HttpWebRequest with the simplicity of WebClient .
var url = "https://your-url.tld/expecting-a-post.aspx" var client = new WebClient(); var method = "POST"; // If your endpoint expects a GET then do it. var parameters = new NameValueCollection(); parameters. Add("parameter1", "Hello world"); parameters. Add("parameter2", "www.stopbyte.com"); parameters.
You can check if the error is of type WebException
and then inspect the response code;
if (e.Error.GetType().Name == "WebException") { WebException we = (WebException)e.Error; HttpWebResponse response = (System.Net.HttpWebResponse)we.Response; if (response.StatusCode==HttpStatusCode.NotFound) System.Diagnostics.Debug.WriteLine("Not found!"); }
or
try { // send request } catch (WebException e) { // check e.Status as above etc.. }
There is a way to do it using reflection. It works with .NET 4.0. It accesses a private field and may not work in other versions of .NET without modifications.
I have no idea why Microsoft did not expose this field with a property.
private static int GetStatusCode(WebClient client, out string statusDescription) { FieldInfo responseField = client.GetType().GetField("m_WebResponse", BindingFlags.Instance | BindingFlags.NonPublic); if (responseField != null) { HttpWebResponse response = responseField.GetValue(client) as HttpWebResponse; if (response != null) { statusDescription = response.StatusDescription; return (int)response.StatusCode; } } statusDescription = null; return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With