RSS

HTTP post in ASP.NET

23 May

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 class.

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 WebRequest class.

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 Content-Length and Content-Type.

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 WebResponse object.

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:

dataStream.Close();
webResponse.Close();

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.

Advertisements
 
Leave a comment

Posted by on May 23, 2009 in ASP.NET

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: