Last time I’ve blogged about getting uploaded files in ASP.NET, today’s post is absolutely opposite – sending data to a web page.
Before sending any data to any URI we have to create an instance of
WebRequest is an abstract class which means that it can handle different protocols (such as HTTP and FTP) and that we actually work with its descendant classes. Instance of what class will be created depends on the URI protocol and also it can be a custom class inherited from
WebRequest. In this article I am working with HTTP-specific implementation of
To create a new
HttpWebRequest object I use
Create method of
WebRequest. In the example below I also prepare data that I want to send and set some properties of
WebRequest for correct HTTP post, such as
WebRequest webRequest = WebRequest.Create(URI); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; string parameters = "REFERENCE=" + refNum + "&STATUS=" + status; byte bytes = Encoding.UTF8.GetBytes(parameters); webRequest.ContentLength = bytes.Length;
Now we are ready to send our status update request to the web page that is located at the specified
URI. For that we need to create a
Stream object and write our data into it.
Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(bytes, 0, bytes.Length); dataStream.Close();
The request has been sent. If you want to get other server’s reply use the same approach but instead of
WebRequest you will need
Let’s read the response and check if it’s “SUCCESS”:
WebResponse webResponse = webRequest.GetResponse(); dataStream = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFields = reader.ReadToEnd(); reader.Close(); if (responseFields.ToString() == "SUCCESS") Response.Write("Hurray!");
When you have finished with reading response data, you must close
WebResponse object either by calling its
Close method or closing the stream. In my example I close both:
As MSDN says, if you do not close the response or the stream, your application can run out of connections to the server and become unable to process additional requests.