Home > Articles > Programming > Windows Programming

This chapter is from the book

This chapter is from the book

Internet Protocols and the .NET Pluggable Protocol Model

When requesting data over the Internet using a standardized protocol such as HTTP (the protocol for the Web), you use a Uniform Resource Identifier (URI) to specify the protocol, server, and name of the resource that you are attempting to access. The .NET Compact Framework provides two abstract classes for handling any Internet resource request and response: System.Net.WebRequest and System.Net.WebResponse.

Client applications use the WebRequest class to make the request for a specific URI from an Internet location over a specific protocol (such as HTTP or FTP). Instead of calling a constructor for the WebRequest class, you initialize a new request by calling the WebRequest.Create() method. This automatically instantiates a new request object based on the protocol that you used for the request. For example, if you are trying to access a resource on the Web using the HTTP protocol, you are returned an HttpWebRequest object for which you can set properties and receive a response stream.

Once your request has been configured, you can call the WebRequest.GetResponse() method to get a Stream class that is used to receive the data from the request.

The WebRequest object is an abstract class that contains the methods and properties described in Table 12.12.

Table 12.12. WebRequest Class Methods and Properties

Method

Description

 

Abort()

Cancels an asynchronous request to an Internet resource

 

BeginGetRequestStream()

Begins an asynchronous GetRequestStream() operation

 

BeginGetResponse()

Begins an asynchronous GetResponse() operation

 

Create()

Creates a new WebRequest object

 

EndGetRequestStream()

Ends an asynchronous GetRequestStream() operation

 

EndGetResponse()

Ends an asynchronous GetResponse() operation

 

GetRequestStream()

Gets a Stream class for writing data to the Internet resource

 

GetResponse()

Gets a WebResponse object that returns the response to an Internet request

 

RegisterPrefix()

Registers a new URI type

 

Property

Get/Set

Description

ConnectionGroupName

Get/set

Abstract property used to get or set the connection group name in descendant classes

ContentLength

Get/set

Abstract property used to get or set the length of the request data

ContentType

Get/set

Abstract property used to get or set the content type of the request

Credentials

Get/set

Abstract property used to get or set the credentials for the request

Headers

Get/set

Abstract property used to get or set the headers and values for the request

Method

Get/set

Abstract property used to get or set the method used for the request

PreAuthenticate

Get/set

Abstract property used to determine whether the request should be preauthenticated

Proxy

Get/set

Abstract property used to get or set the proxy to be used for the request

RequestUri

Get/set

Abstract property used to get or set the URI for the request

Timeout

Get/set

Abstract property used to get or set the length of time before the request times out

The WebResponse object is also abstract, and contains the methods and properties described in Table 12.13.

Table 12.13. WebResponse Class Methods and Properties

Method

Description

 

Close()

Closes the response stream

 

GetResponseStream()

Gets the Stream for reading the response

 

Property

Get/Set

Description

ContentLength

Get/set

Abstract property used to get or set the length of the data being received

ContentType

Get/set

Abstract property used to get or set the content type for the data being received

Headers

Get/set

Abstract property used to get or set the headers and values of the request

RequestUri

Get/set

Abstract property used to get or set the URI for the resource requested

Both the WebRequest and WebResponse abstract classes form the basis for what is known as pluggable protocols. The concept of pluggable protocols is fairly straightforward—a client application can make a request for any Internet resource using a URI and not have to worry about the underlying details of the network protocol being used. When a request is made using the WebRequest.Create() method, the appropriate protocol-specific class is automatically instantiated and returned to the client application.

Consider the following request for a Web resource:

// Set up the URI
System.Uri urlRequest = new System.Uri("http://www.furrygoat.com/");

// Make the request
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.
  Create(urlRequest);

// Get the response
HttpWebResponse webResponse = (HttpWebResponse)httpReq.
  GetResponse();

This request will return a new object that is based on the HttpWebRequest class. The HttpWebRequest class is actually derived from WebRequest, but adds all of the protocol specifics surrounding HTTP.

What makes the pluggable protocol model extremely useful is that you can also use it to create your own classes for handling new protocols that are not native to the .NET Compact Framework.

Creating a Pluggable Protocol

Any new class that is designed to be used as a pluggable protocol is always derived from WebRequest and WebResponse. All new pluggable protocol classes must also be registered with the base WebRequest object in order for the WebRequest.Create() method to appropriately instantiate the correct object for the protocol.

To register a new protocol with the WebRequest class, you can use the following function:

public static bool WebRequest.RegisterPrefix(string prefix,
   IWebRequestCreate creator);

The first parameter, prefix, is a string that represents the protocol that will be used in URI requests for the new object. For example, if you were creating a new protocol that handled requests for resources over the File Transfer Protocol (such as ftp://ftp.microsoft.com/dir/filename.txt), you could simply use ftp for the prefix value. The creator parameter should be set to an object that implements the IWebRequestCreate interface, which is used to create the new WebRequest class.

The following code shows the basic layout for creating a new protocol-specific class that can be used by the WebRequest.Create() method:

/// <summary>Ftp request protocol handler</summary>
class FtpWebRequest: WebRequest {
   // Private internal variables.
   private NetworkCredential reqCredentials;
   private WebHeaderCollection reqHeaders;
   private WebProxy reqProxy;
   private System.Uri reqUri;
   private string reqConnGroup;
   private long reqContentLength;
   private string reqContentType;
   private string reqMethod;
   private bool reqPreAuthen;
   private int reqTimeout;

   // Constructor
   public FtpWebRequest(System.Uri uri) {
      reqHeaders = new WebHeaderCollection();
      reqUri = uri;
   }

   // Properties
   public override string ConnectionGroupName {
      get { return reqConnGroup; }
      set { reqConnGroup = value; }
   }
   public override long ContentLength {
      get { return reqContentLength; }
      set { reqContentLength = value; }
   }
   public override string ContentType {
      get { return reqContentType; }
      set { reqContentType = value; }
   }
   public override ICredentials Credentials {
      get { return reqCredentials; }
      set { reqCredentials = (System.Net.NetworkCredential)
         value; }
   }
   public override WebHeaderCollection Headers {
      get { return reqHeaders; }
      set { reqHeaders = value; }
   }
   public override string Method {
      get { return reqMethod; }
      set { reqMethod = value; }
   }
   public override bool PreAuthenticate {
      get { return reqPreAuthen; }
      set { reqPreAuthen = value; }
   }
   public override IWebProxy Proxy {
      get { return reqProxy; }
      set { reqProxy = (System.Net.WebProxy)value; }
   }
   public override Uri RequestUri {
      get { return reqUri; }
   }
   public override int Timeout {
      get { return reqTimeout; }
      set { reqTimeout = value; }
   }

   // Methods. These are just stubbed in here for this example.
   // In an actual FTP client, you would need to implement these by
   // using p/Invoke to call into the WinInet FTP functions.
   public override void Abort() {
      base.Abort();
   }
   public override IAsyncResult BeginGetRequestStream
     (AsyncCallback callback, object state) {
     return base.BeginGetRequestStream (callback, state);
   }
   public override IAsyncResult BeginGetResponse
      (AsyncCallback callback, object state) {
      return base.BeginGetResponse (callback, state);
   }
   public override Stream EndGetRequestStream(IAsyncResult
      asyncResult) {
      return base.EndGetRequestStream (asyncResult);
   }
   public override WebResponse EndGetResponse(IAsyncResult
      asyncResult) {
      return base.EndGetResponse (asyncResult);
   }
   public override Stream GetRequestStream() {
      return base.GetRequestStream();
   }
   public override WebResponse GetResponse() {
      return base.GetResponse();
   }
}
/// <summary>Ftp request registration interface</summary>
class FtpWebRequestCreate: IWebRequestCreate {
   public System.Net.WebRequest Create(System.Uri uri) {
      System.Net.WebRequest request = new FtpWebRequest
         (uri);
      return request;
   }
}

/// <summary>Ftp request response handler</summary>
class FtpWebResponse: WebResponse {
   // Private internal variables.
   private WebHeaderCollection respHeaders;
   private System.Uri respUri;
   private long respContentLength;
   private string respContentType;

   // Properties
   public override long ContentLength {
      get { return respContentLength; }
      set { respContentLength = value; }
   }
   public override string ContentType {
      get { return respContentType; }
      set { respContentType = value; }
   }
   public override WebHeaderCollection Headers {
      get { return respHeaders; }
      set { respHeaders = value; }
   }
   public override Uri ResponseUri {
      get { return reqUri; }
   }

   // Methods. These are just stubbed in here for this example.
   // In an actual FTP client, you would need to implement these by
   // using p/Invoke to call into the WinInet FTP functions.
   public override void Close() {
      base.Close();
   }
   public override Stream GetResponseStream() {
      return base.GetResponseStream();
   }
}

Remember that you also need to register the protocol with the WebRequest class in order for it to be properly instantiated:

class FtpTest {
   static void Main(string[] args) {
      // Create a pluggable protocol
      System.Uri urlRequest = new
         System.Uri("ftp://ftp.microsoft.com/developr/
            readme.txt");

      // Register it
      WebRequest.RegisterPrefix("ftp", new
         FtpWebRequestCreate());

      // Make the request
      FtpWebRequest ftpClient = (FtpWebRequest)WebRequest.
         Create(urlRequest);

      // Get the response
      FtpWebResponse ftpResponse = (FtpWebResponse)
         ftpClient.GetResponse();

      // Use a StreamReader class to read in the response
      StreamReader responseStream = new
         StreamReader(ftpResponse.GetResponseStream(),
         System.Text.Encoding.ASCII);

      // Since FTP can be binary or ASCII, you would want
      // to copy it in chunks to the destination file...

      // Close the stream
      responseStream.Close();
   }
}

Accessing Content on the Web

One of the built-in pluggable protocols available in the .NET Compact Framework for handling HTTP and HTTPS requests to the Internet is the HttpWebRequest class. As with any other protocol-specific class, it has been derived from the WebRequest class and can be created by using the WebRequest.Create() method:

HttpWebRequest httpReq =
   (HttpWebRequest)WebRequest.Create("http://www.
   furrygoat.com");

The HttpWebRequest class contains the methods and properties described in Table 12.14.

Table 12.14. HttpWebRequest Class Methods and Properties

Method

Description

 

Abort()

Cancels an asynchronous request to an Internet resource

 

AddRange()

Adds a Range header to the request

 

BeginGetRequestStream()

Begins an asynchronous GetRequestStream() operation

 

BeginGetResponse()

Begins an asynchronous GetResponse() operation

 

EndGetRequestStream()

Ends an asynchronous GetRequestStream() operation

 

EndGetResponse()

Ends an asynchronous GetResponse() operation

 

GetRequestStream()

Gets a Stream class for writing data to the Internet resource

 

GetResponse()

Gets a WebResponse object that returns the response to an Internet request

 

RegisterPrefix()

Registers a new URI type

 

Property

Get/Set

Description

Accept

Get/set

Gets or sets the HTTP Accept header

Address

Get

Gets the URI of the resource that responded to the request

AllowAutoRedirect

Get/set

Indicates whether the request should follow a redirect

AllowWriteStreamBuffering

Get/set

Indicates whether to buffer the data sent to the resource

Connection

Get/set

Gets or sets the HTTP Connection header

ConnectionGroupName

Get/set

Gets or sets the name of the connection group

ContentLength

Get/set

Gets or sets the HTTP Content-Length header

ContentType

Get/set

Gets or sets the HTTP Content-Type header

ContinueDelegate

Get/set

Gets or sets the delegate for HTTP requests

Credentials

Get/set

Gets or sets credentials for the request

Expect

Get/set

Gets or sets the HTTP Expect header

Headers

Get

Gets the collection of HTTP headers for the request

IfModifiedSince

Get/set

Gets or sets the HTTP If-Modified-Since header

KeepAlive

Get/set

Indicates whether or not the HTTP request should use a persistent connection

MaximumAutomatic Redirections

Get/set

Gets or sets the number of HTTP redirects the request will comply with

MediaType

Get/set

Gets or sets the media type of the request

Method

Get/set

Gets or sets the HTTP method used with the request

Pipelined

Get/set

Indicates whether the request is pipelined

PreAuthenticate

Get/set

Indicates whether to pre-authenticate a request

ProtocolVersion

Get/set

Gets or sets the HTTP version to use with the request

Proxy

Get/set

Gets or sets proxy information

Referer

Get/set

Gets or sets the HTTP Referer header

RequestUri

Get

Gets the original request URI

SendChunked

Get/set

Indicates whether to send the data in segments

ServicePoint

Get

Gets the service point for the request

Timeout

Get/set

Gets or sets the time-out value

TransferEncoding

Get/set

Gets or sets the HTTP Transfer-Encoding header

UserAgent

Get/set

Gets or sets the HTTP User-Agent header

To get the results for the request that was made by the HttpWebRequest object, you can use the GetResponse() method:

HttpWebResponse webResponse =
   (HttpWebResponse)httpReq.GetResponse();

The HttpWebResponse class supports the methods and properties described in Table 12.15.

Table 12.15. HttpWebResponse Class Methods and Properties

Method

Description

 

Close()

Closes the response stream

 

GetResponseHeader()

Gets the header that was returned for the response

 

GetResponseStream()

Gets the Stream for reading the response

 

Property

Get/Set

Description

CharacterSet

Get

Gets the character set for the response

ContentEncoding

Get

Gets the encoding scheme used for the response

ContentLength

Get

Gets the length of the response

ContentType

Get

Gets the type of the response

Headers

Get

Gets the headers associated with the response

LastModified

Get

Gets the last modified time of the response

Method

Get

Gets the method used to return the response

ProtocolVersion

Get

Gets the HTTP version used for the response

ResponseUri

Get

Gets the URI of the resource that responded to the request

Server

Get

Gets the name of the server that sent the response

StatusCode

Get

Gets the HTTP status code for the response

StatusDescription

Get

Gets the HTTP status description for the response

The following code shows how to create a new request for a Web resource, using the StreamReader class to read in the response that you receive from the Web server:

using System;
using System.Data;
using System.Net;
using System.IO;

namespace WebSample {
   class WebTest {
      static void Main(string[] args) {
         // Make a new WebRequest object
         System.Uri urlRequest = new
            System.Uri("http://www.furrygoat.com/");
         HttpWebRequest webClient = (HttpWebRequest)
            WebRequest.Create(urlRequest);

         // Get the response
         HttpWebResponse webResponse = (HttpWebResponse)
            webClient.GetResponse();

         // Use a StreamReader class to read in the response
         StreamReader responseStream = new StreamReader(
            webResponse.GetResponseStream(),
            System.Text.Encoding.ASCII);

         // Copy the stream to a string, do something with it
         // string strResponse = responseStream.ReadToEnd();

         // Close the stream
         responseStream.Close();
      }
   }
}

The response stream, strResponse, contains the HTML code that was downloaded from the Web site:

<HTML>
<title>The Furrygoat Experience</title>
<body>
<p><b><font face="Arial">This is the Furrygoat homepage!
  </font></b></p>
</body>
</HTML>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020