9.2 Generic Request/Response Architecture

The request/response architecture is based on Uniform Resource Indicator (URI) and stream I/O, follows the factory design pattern, and makes good use of abstract types and interfaces. A factory method, WebRequest.Create( ), parses the URI and creates the appropriate protocol handler to fulfill the request.

Protocol handlers share a common abstract base type (WebRequest), which exposes properties that configure the request and methods used to retrieve the response.

Responses are also represented as types and share a common abstract base type (WebResponse), which exposes a NetworkStream, providing a simple streams-based I/O and easy integration into the rest of the FCL.

This example is a simple implementation of the popular Unix snarf utility. It demonstrates the use of the WebRequest and WebResponse classes to retrieve the contents of a URI and print them to the console:

// Snarf.cs
// Run Snarf.exe <http-uri> to retrieve a web page
// e.g. snarf.exe http://www.oreilly.com/catalog/csharpnut/
using System;
using System.IO;
using System.Net;
using System.Text;
class Snarf {
  static void Main(string[ ] args) {
    // Retrieve the data at the URL with a WebRequest instance
    WebRequest req = WebRequest.Create(args[0]);
    WebResponse resp = req.GetResponse( );
    // Read in the data, performing ASCII->Unicode encoding
    Stream s = resp.GetResponseStream( );
    StreamReader sr = new StreamReader(s, Encoding.ASCII);
    string doc = sr.ReadToEnd( );
    Console.WriteLine(doc); // Print result to console

    Part II: Programming with the .NET Framework
    Part IV: API Quick Reference
    Evaluation has БСєЛЪexpired.