- Networking with the Compact Framework
- Winsock and .NET
- Internet Protocols and the .NET Pluggable Protocol Model
- Consuming Web Services
- Pocket PC and P/Invoke
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>