Internet Access Fundamentals


The classes contained in System.Net support a request/response model of Internet interaction. In this approach, your program, which is the client, requests information from the server and then waits for the response. For example, as a request, your program might send to the server the URI of some web site. The response that you will receive is the hypertext associated with that URI. This request/response approach is both convenient and simple to use because most of the details are handled for you.

The hierarchy of classes topped by WebRequest and WebResponse implement what Microsoft calls pluggable protocols. As most readers know, there are several different types of network communication protocols. The most common for Internet use is HTTP (Hypertext Transfer Protocol). Another is FTP (File Transfer Protocol). When a URI is constructed, the prefix of the URI specifies the protocol. For example, HTTP://MyWebSite.com uses the prefix HTTP, which specifies hypertext transfer protocol.

As mentioned earlier, WebRequest and WebResponse are abstract classes that define the general request/response operations that are common to all protocols. From them are derived concrete classes that implement specific protocols. Derived classes register themselves, using the static method RegisterPrefix( ), which is defined by WebRequest. When you create a WebRequest object, the protocol specified by the URI’s prefix will automatically be used, if it is available. The advantage of this “pluggable” approach is that most of your code remains the same no matter what type of protocol you are using.

The .NET runtime automatically defines the HTTP, HTTPS, file, and FTP protocols. (Support for FTP was added by C# 2.0.) Thus, if you specify a URI that uses the HTTP prefix, you will automatically receive the HTTP-compatible class that supports it. If you specify a URI that uses the FTP prefix, you will automatically receive the FTP-compatible class that supports it.

Because HTTP is the most commonly used protocol, it is the only one discussed in this chapter. (However, the same techniques will apply to all supported protocols.) The classes that support HTTP are HttpWebRequest and HttpWebResponse. These classes inherit WebRequest and WebResponse, and add several members of their own, which apply to the HTTP protocol.

System.Net supports both synchronous and asynchronous communication. For many Internet uses, synchronous transactions are the best choice because they are easy to use. With synchronous communications, your program sends a request and then waits until the response is received. For some types of high-performance applications, asynchronous communication is better. Using the asynchronous approach, your program can continue processing while waiting for information to be transferred. However, asynchronous communications are more difficult to implement. Furthermore, not all programs benefit from an asynchronous approach. For example, often when information is needed from the Internet, there is nothing to do until the information is received. In cases like this, the potential gains from the asynchronous approach are not realized. Because synchronous Internet access is both easier to use and more universally applicable, it is the only type examined in this chapter.

Since WebRequest and WebResponse are at the heart of System.Net, they will be examined next.

WebRequest

The WebRequest class manages a network request. It is abstract because it does not implement a specific protocol. It does, however, define those methods and properties common to all requests. The methods defined by WebRequest that support synchronous communications are shown in Table 24-1. The properties defined by WebRequest are shown in Table 24-2. The default values for the properties are determined by derived classes. WebRequest defines no public constructors.

Table 24-1: The Methods Defined by WebRequest That Support Synchronous Communications

Method

Description

public static WebRequest Create(string uri);

Creates a WebRequest object for the URI specified by the string passed by uri. The object returned will implement the protocol specified by the prefix of the URI. Thus, the object will be of a class that inherits WebRequest. A NotSupportedException is thrown if the requested protocol is not available. A UriFormatException is thrown if the URI format is invalid.

public static WebRequest Create(Uri uri);

Creates a WebRequest object for the URI specified by uri. The object returned will implement the protocol specified by the prefix of the URI. Thus, the object will be of a class that inherits WebRequest. A NotSupportedException is thrown if the requested protocol is not available.

public virtual Stream GetRequestStream( )

Returns an output stream associated with the previously requested URI.

public virtual WebResponse GetResponse( )

Sends the previously created request and waits for a response. When a response is received, it is returned as a WebReponse object. Your program will use this object to obtain information from the specified URI.

Table 24-2: The Properties Defined by WebRequest

Property

Description

public AuthenticationLevel AuthenticationLevel( get; set; }

Obtains or sets the authentication level. (Added by C# 2.0.)

public virtual RequestCachePolicy CachePolicy { get; set; }

Obtains or sets the cache policy, which controls when a response can be obtained from the cache. (Added by C# 2.0.)

public virtual string ConnectionGroupName { get; set; }

Obtains or sets the connection group name. Connection groups are a way of creating a set of requests. They are not needed for simple Internet transactions.

public virtual long ContentLength { get; set; }

Obtains or sets the length of the content.

public virtual string ContentType { get; set; }

Obtains or sets the description of the content.

public virtual ICredentials Credentials { get; set; }

Obtains or sets credentials.

public static RequestCachePolicy DefaultCachePolicy { get; set; }

Obtains or sets the default cache policy, which controls when a request can be obtained from the cache. (Added by C# 2.0.)

public static IWebProxy DefaultWebProxy { get; set; }

Obtains or sets the default proxy. (Added by C# 2.0.)

public virtual WebHeaderCollection Headers{ get; set; }

Obtains or sets a collection of the headers.

public TokenImpersonationLevel ImpersonationLevel { get; set; }

Obtains or sets the impersonation level. (Added by C# 2.0.)

public virtual string Method { get; set; }

Obtains or sets the protocol.

public virtual bool PreAuthenticate { get; set; }

If true, authentication information is included when the request is sent. If false, authentication information is provided only when requested by the URI.

public virtual IWebProxy Proxy { get; set; }

Obtains or sets the proxy server. This applies only to environments in which a proxy server is used.

public virtual Uri RequestUri { get; }

Obtains the URI of the request.

public virtual int Timeout { get; set; }

Obtains or sets the number of milliseconds that a request will wait for a response. To wait forever, use Timeout.Infinite.

public virtual bool UseDefaultCredentials { get; set; }

Obtains or sets a value that determines if default credentials are used for authentication. If true, the default credentials (i.e., those of the user) are used. They are not used if false. (Added by C# 2.0.)

To send a request to a URI, you must first create an object of a class derived from WebRequest that implements the desired protocol. This is done by calling Create( ), which is a static method defined by WebRequest. Create( ) returns an object of a class that inherits WebRequest and implements a specific protocol.

WebResponse

WebResponse encapsulates a response that is obtained as the result of a request. WebResponse is an abstract class. Inheriting classes create specific, concrete versions of it that support a protocol. A WebResponse object is normally obtained by calling the GetResponse( ) method defined by WebRequest. This object will be an instance of a concrete class derived from WebReponse that implements a specific protocol. The methods defined by WebResponse are shown in Table 24-3. The properties defined by WebResponse are shown in Table 24-4. The values of these properties are set based on each individual response. WebResponse defines no public constructors.

Table 24-3: The Methods Defined by WebResponse

Method

Description

public virtual void Close( )

Closes the response. It also closes the response stream returned by GetResponseStream( ).

public virtual Stream GetResponseStream( )

Returns an input stream connected to the requested URI. Using this stream, data can be read from the URI.

Table 24-4: The Properties Defined by WebResponse

Property

Description

public virtual long ContentLength { get; set; }

Obtains or sets the length of the content being received. This will be 1 if the content length is not available.

public virtual string ContentType { get; set; }

Obtains or sets a description of the content.

public virtual WebHeaderCollection Headers { get; }

Obtains a collection of the headers associated with the URI.

public virtual bool IsFromCache { get; }

If the response came from the cache, this property is true. It is false if the response was delivered over the network. (Added by C# 2.0.)

public virtual bool IsMutuallyAuthenticated { get; }

If the client and server are both authenticated, then this property is true. It is false otherwise. (Added by C# 2.0.)

public virtual Uri ReponseUri { get; }

Obtains the URI that generated the response. This may differ from the one requested if the response was redirected to another URI.

HttpWebRequest and HttpWebResponse

The classes HttpWebRequest and HttpWebResponse inherit the WebRequest and WebResponse classes and implement the HTTP protocol. In the process, both add several properties that give you detailed information about an HTTP transaction. Some of these properties are used later in this chapter. However, for simple Internet operations, you will not often need to use these extra capabilities.

A Simple First Example

Internet access centers around WebRequest and WebResponse. Before we examine the process in detail, it will be useful to see an example that illustrates the request/response approach to Internet access. After you see these classes in action, it is easier to understand why they are organized as they are.

The following program performs a simple, yet very common, Internet operation. It obtains the hypertext contained at a specific web site. In this case, the content of McGraw-Hill.com is obtained, but you can substitute any other web site. The program displays the hypertext on the screen in chunks of 400 characters, so you can see what is being received before it scrolls off the screen.

 // Access the Internet. using System; using System.Net; using System.IO; class NetDemo {   public static void Main() {     int ch;     // First, create a WebRequest to a URI.     HttpWebRequest req = (HttpWebRequest)            WebRequest.Create("http://www.McGraw-Hill.com");     // Next, send that request and return the response.     HttpWebResponse resp = (HttpWebResponse)            req.GetResponse();     // From the response, obtain an input stream.     Stream istrm = resp.GetResponseStream();     /* Now, read and display the html present at        the specified URI.  So you can see what is        being displayed, the data is shown        400 characters at a time.  After each 400        characters are displayed, you must press        ENTER to get the next 400. */     for(int i=1; ; i++) {       ch =  istrm.ReadByte();       if(ch == -1) break;       Console.Write((char) ch);       if((i%400)==0) {         Console.Write("\nPress Enter.");         Console.ReadLine();       }     }     // Close the Response. This also closes istrm.     resp.Close();   } }

The first part of the output is shown here. (Of course, over time this content will differ from that shown here.)

 <html> <head> <title>Home - The McGraw-Hill Companies</title> <meta name="keywords" content="McGraw-Hill Companies,McGraw-Hill, McGraw Hill, Aviation Week, BusinessWeek, Standard and Poor's, Standard & Poor's,CTB/McGraw-Hill,Glencoe/McGraw-Hill, The Grow Network/McGraw-Hill,Macmillan/McGraw-Hill, McGraw-Hill Contemporary,McGraw-Hill Digital Learning, McGraw-Hill Professional Development,SRA/McGraw-Hi Press Enter. ll,Wright Group/McGraw-Hill,McGraw-Hill Higher Education, McGraw-Hill/Irwin,McGraw-Hill/Primis Custom Publishing, McGraw-Hill/Ryerson,Tata/McGraw-Hill, McGraw-Hill Interamericana,Open University Press, Healthcare Information Group, Platts, McGraw-Hill Construction, Information & Media Services" /> <meta name="description" content="The McGraw-Hill Companies Corporate Website." /> <meta http-equiv="Con Press Enter. tent-Type" content="text/html; charset=iso-8859-1"> <META HTTP-EQUIV="Refresh" CONTENT="900"> <META HTTP-EQUIV="EXPIRES" CONTENT="-1"> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <link rel="stylesheet" href="stylesheet.css" type="text/css" media="screen,projection"> <link rel="stylesheet" href="print.css" type"text/css" media="print"> <script language="JavaScript1.2" src="/books/3/12/1/html/2/scripts.js"></script> Press Enter.

This is part of the hypertext associated with the McGraw-Hill.com web site. Since the program simply displays the content character-by-character, it is not formatted as it would be by a browser. It is displayed in its raw form.

Let’s examine this program line-by-line. First, notice that the System.Net namespace is used. As explained, this is the namespace that contains the networking classes. Also notice that System.IO is included. This namespace is needed because the information from the web site is read using a Stream object.

The program begins by creating a WebRequest object that contains the desired URI. Notice that the Create( ) method, rather than a constructor, is used for this purpose. Create( ) is a static member of WebRequest. Even though WebRequest is an abstract class, it is still possible to call a static method of that class. Create( ) returns a WebRequest object that has the proper protocol “plugged in,” based on the protocol prefix of the URI. In this case, the protocol is HTTP. Thus, Create( ) returns an HttpWebRequest( ) object. Of course, its return value must still be cast to HttpWebRequest when it is assigned to the HttpWebRequest reference called req. At this point, the request has been created, but not yet sent to the specified URI.

To send the request, the program calls GetResponse( ) on the WebRequest object. After the request has been sent, GetResponse( ) waits for a response. Once a response has been received, GetResponse( ) returns a WebResponse object that encapsulates the response. This object is assigned to resp. Since, in this case, the response uses the HTTP protocol, the result is cast to HttpWebResponse. Among other things, the response contains a stream that can be used to read data from the URI.

Next, an input stream is obtained by calling GetResponseStream( ) on resp. This is a standard Stream object, having all of the attributes and features of any other input stream. A reference to the stream is assigned to istrm. Using istrm, the data at the specified URI can be read in the same way that a file is read.

Next, the program reads the data from McGraw-Hill.com and displays it on the screen. Since there is a lot of information, the display pauses every 400 characters and waits for you to press enter. This way the first part of the information won’t simply scroll off the screen. Notice that the characters are read using ReadByte( ). Recall that this method returns the next character from the input stream as an int, which must be cast to char. It returns 1 when the end of the stream has been reached.

Finally, the response is closed by calling Close( ) on resp. Closing the response stream automatically closes the input stream, too. It is important to close the response between each request. If you don’t, it is possible to exhaust the network resources and prevent the next connection.

Before leaving this example, one other important point needs to be made: It was not actually necessary to use an HttpWebRequest or HttpWebResponse object to display the hypertext received from the server. Because the preceding program did not use any HTTP-specific features, the standard methods defined by WebRequest and WebResponse were sufficient to handle this task. Thus, the calls to Create( ) and GetResponse( ) could have been written like this:

 // First, create a WebRequest to a URI. WebRequest req =  WebRequest.Create("http://www.McGraw-Hill.com"); // Next, send that request and return the response. WebResponse resp =  req.GetResponse();

In cases in which you don’t need to employ a cast to a specific type of protocol implementation, it is better to use WebRequest and WebResponse, because it allows protocols to be changed with no impact on your code. However, since all of the examples in this chapter will be using HTTP, and a few will be using HTTP-specific features, the programs will use HttpWebRequest and HttpWebResponse.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net