Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

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); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

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

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard

Publisher Resources

ISBN: 0596005261Catalog PageErrata