You want to send a request to a web server in the form of a GET or POST request. After you send the request to a web server, you want to get the results of that request (the response) from the web server. The WebRequest and WebResponse classes of System.Net namespace encapsulate all of the functionality to perform basic web transactions. HttpWebRequest and HttpWebResponse are derived classes from these, respectively, and provide the HTTP specific web transaction support.

Use the HttpWebRequest class in conjunction with the WebRequest class to create and send a request to a server. Take the URI of the resource, the method to use in the request (GET or POST), and the data to send (only for POST requests), and use this information to create an HttpWebRequest:

using System.Net;
using System.IO;
using System.Text;

// ...

public static HttpWebRequest GenerateGetOrPostRequest(string uriString,
    string method,
    string postData)
{
    if ((method.ToUpper() != "GET") &&
        (method.ToUpper() != "POST"))
            throw new ArgumentException(method +
               " is not a valid method.  Use GET or POST.","method");

    HttpWebRequest httpRequest = null;
    // get a URI object
    Uri uri = new Uri(uriString);
    // create the initial request
    httpRequest = (HttpWebRequest)WebRequest.Create(uri);

    // check if asked to do a POST request, if so then modify
    // the original request as it defaults to a GET method
    if (method.ToUpper()=="POST")
    {
        // Get the bytes for the request, should be pre-escaped
        byte[] bytes = Encoding.UTF8.GetBytes(postData); 

        // Set the content type of the data being posted.
        httpRequest.ContentType =
            "application/x-www-form-urlencoded";

        // Set the content length of the string being posted.
        httpRequest.ContentLength = postData.Length;

        // Get the request stream and write the post data in
        Stream requestStream = httpRequest.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        // Done updating for POST so close the stream
        requestStream.Close();
    }

    // return the request
    return httpRequest;
}

Once we have an HttpWebRequest, we send the request and get the response using the GetResponse method that takes our newly created HttpWebRequest as input and returns an HttpWebResponse. In this example, we perform a GET for the index.aspx page from the http://localhost/mysite web site:

public enum ResponseCategories
{
    Unknown = 0,        // unknown code  ( < 100 or > 599)
    Informational = 1,  // informational codes (100 <= 199)
    Success = 2,        // success codes (200 <= 299)
    Redirected = 3,     // redirection code (300 <= 399)
    ClientError = 4,    // client error code (400 <= 499)
    ServerError = 5     // server error code (500 <= 599)
}
...
public static ResponseCategories VerifyResponse(HttpWebResponse httpResponse)
{
    // Just in case there are more success codes defined in the future
    // by HttpStatusCode, we will check here for the "success" ranges
    // instead of using the HttpStatusCode enum as it overloads some
    // values
    int statusCode = (int)httpResponse.StatusCode;
    if ((statusCode >= 100) && (statusCode <= 199))
    {
        return ResponseCategories.Informational;
    }
    else if ((statusCode >= 200) && (statusCode <= 299))
    {
        return ResponseCategories.Success;
    }
    else if ((statusCode >= 300) && (statusCode <= 399))
    {
        return ResponseCategories.Redirected;
    }
    else if ((statusCode >= 400) && (statusCode <= 499))
    {
        return ResponseCategories.ClientError;
    }
    else if ((statusCode >= 500) && (statusCode <= 599))
    {
        return ResponseCategories.ServerError;
    }
    return ResponseCategories.Unknown;
}

...

HttpWebRequest request =
 GenerateGetOrPostRequest("http://localhost/mysite/index.aspx",
                               "GET",
                               null);

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

if (VerifyResponse(response) == ResponseCategories.Success)
{
    Console.WriteLine("Request succeeded");
}

At the most fundamental level, to perform an HTTP-based web transaction, you use the Create method on the WebRequest class to get a WebRequest that can be cast to an HttpWebRequest (so long as the the scheme is http:// or https://). This HttpWebRequest is then submitted to the web server in question when the GetResponse method is called, and it returns an HttpWebResponse that can then be inspected for the response data.

Popularity: 6% [?]