Using HttpWebRequest class to make web request against Http server

Hi,

 

Many a times comes a situation, where we have to make call//request to another page through http protocol. The requirement might come when you want to fetch data from another page through http protocol, or just make a request to start some process which gets started on the page request itself.

 

For this kind of requirement we have the HttpWebRequest class in the System.Net namespace. The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP. Remember, for security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to enable cookies.

 

Below is a small code snippet on how to use the class to request fro a page.

 

string strIcrawlURL = @"URLOfThePage";

WebRequest mObjWebRequest = null;

WebResponse mObjWebResponse = null;

Stream mObjReceiveStream = null;

string strResponse = string.Empty;

          

try

{

mObjWebRequest = WebRequest.Create(strIcrawlURL);

//// Use the default credential for accessing the page

mObjWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

//// Send the 'WebRequest' and wait for response.

mObjWebResponse = mObjWebRequest.GetResponse();

//// Obtain a 'Stream' object associated with the response object.

mObjReceiveStream = mObjWebResponse.GetResponseStream();

//// Pipe the stream to a higher level stream reader with the required encoding format.

StreamReader readStream = new StreamReader(mObjReceiveStream, System.Text.Encoding.GetEncoding("utf-8"));

strResponse = readStream.ReadToEnd();

readStream.Close();

//////// Release the resources of response object.

mObjWebResponse.Close();            

}

catch (Exception ex)

{
//// Do something here for exception raised if any

}

finally

{

mObjWebRequest = null;

mObjWebResponse = null;

mObjReceiveStream = null;

}           

 

Vikram


Share this post   Email it

Feedback

Posted on 3/26/2009 5:27:46 AM

That's nice mate. I am looking to appear for MCTS exam. There are lots of forum for JCP (Java Certification) but couldn't find any for Microsoft. What is exam fees for MCTS ?
It will be great if you can guide me on resources for MCTS.

Many Congrats on your getting MVP award.

Posted on 3/26/2009 5:40:26 AM

Hi Lalit,

You can find more information at www.learnandcertify.com.

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Copyright © 2006 - 2012 Vikram Lakhotia