O'Reilly logo

C# in a Nutshell by Peter Drayton, Ted Neward, Ben Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 an WebRequest ABC 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required