Using the HttpWebRequest Class
Using the HttpWebRequest Class
Last week I got a
requirement for a
direct interaction
with an HTTP
server. As a result I
needed to use the
HttpWebRequest class in
order to create the relevant requests.
This post will introduce the HttpWebRequest class.
The HttpWebRequest Class
The HttpWebRequest class is a wrapper class that wrap an HTTP
request for a resource. It provides many properties and methods that
enable us to configure an HTTP request and interact with HTTP servers.
You should initialize an HttpWebRequest only through the WebRequest’s
Create method like in the following example:
var request = (HttpWebRequest)WebRequest.Create("http://blogs.microsoft.co.il");
The most useful methods that you should know are the GetResponse,
which returns an HttpWebResponse, and BeginGetResponse and EndGetResponse
methods which enables the making of asynchronous request to the relevant
resource. The following example shows how get a response from a HttpWebRequest
object:
var response = (HttpWebResponse)request.GetResponse();
Example of Using the HttpWebRequest Class
The following code is an example of how to use the HttpWebRequest in
order to get the web page of http://blogs.microsoft.co.il (this site)
as a string:
try
{
var request = (HttpWebRequest)WebRequest.Create("http://blogs.microsoft.co.il");
request.Method = "GET";
request.ContentType = "text/html";
request.KeepAlive = false;
request.UseDefaultCredentials = true;
var response = (HttpWebResponse)request.GetResponse();
using (var stream = new StreamReader(response.GetResponseStream()))
{
var result = stream.ReadToEnd();
return result;
}
}
catch (WebException ex)
{
// do something
}
catch (Exception ex)
{
// do something
}
Summary
In this post we saw the HttpWebRequest class and how to use it
to get a resource like a web page to our application. The HttpWebRequest
enables us to communicate with HTTP servers by building the relevant
requests we want to perform and sending them. There are many
other details about this class that I encourage you to check out. Just
Google it/Bing it and you’ll find more details.