Contents
Overview 1
Internet Application Scenarios 2
The WebRequest and WebResponse Model 3
Application Protocols 16
Handling Errors 25
Security 28
Best Practices 35
Lab 11: Creating a DateTime Client/Server
Application 36
Review 41
Course Evaluation 43
Module 11:
Internet Access
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001-2002 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 11: Internet Access iii
Instructor Notes
After completing this module, students will be able to:
!
Use the basic request/response model to send and receive data over the
Internet.
!
Use the System.Net classes to communicate with other applications by
using the HTTP, Transmission Control Protocol (TCP), User Datagram
Protocol (UDP), and Socket Internet protocols.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the Microsoft
®
PowerPoint
®
file 2349B_11.ppt.
Preparation Tasks
To prepare for this module, you should:
!
Read all of the materials for this module.
!
Complete the lab.
Presentation:
60 Minutes
Lab:
45 Minutes
iv Module 11: Internet Access
Module Strategy
Use the following strategy to present this module:
!
Internet Application Scenarios
Briefly introduce examples of Internet applications that use the System.Net
classes, including server-side ASP.NET applications, peer-to-peer Microsoft
Windows
®
Forms applications that act as servers and clients to send and
receive data, and client applications that periodically access the network for
updates.
!
The WebRequest and WebResponse Model
Introduce the WebRequest and WebResponse model. Explain how the
Microsoft .NET Framework uses the Uniform Resource Identifier (URI) to
identify the desired communication protocol and Internet resource. Discuss
network streams as the means of obtaining and receiving Web data.
Explain how to use the WebRequest class to request data from a server,
invoke the request for the Internet resource, and send data through a
network stream. Discuss how the WebResponse.GetResponseStream
method serves as the means of obtaining a stream that contains response
data from a network resource.
!
Application Protocols
Discuss the HTTP, TCP, and UDP protocol support that is provided in the
.NET Framework, as well as information about using the Windows Sockets
interface to implement custom protocols.
!
Handling Errors
Discuss how the WebRequest and WebResponse classes can throw system
exceptions, such as InvalidArgumentException, and Web-specific
exceptions, which are instances of WebException and thrown by the
GetResponse method.
!
Security
Explain how an application can provide security for sending and receiving
data over the Internet by using a Web proxy, Secure Sockets Layer (SSL)
encryption, Internet authentication, and the NET Framework code access
permissions.
!
Best Practices
Briefly outline the list of recommendations that will help students use the
classes that are contained in System.Net more effectively.
Module 11: Internet Access 1
Overview
!
Internet Application Scenarios
!
The WebRequest and WebResponse Model
!
Application Protocols
!
Handling Errors
!
Security
!
Best Practices
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The Microsoft
®
.NET Framework System.Net and System.Net.Sockets
namespaces provide a layered, extensible, and managed implementation of
Internet protocols that applications can use to send or receive data over the
Internet. The System.Net classes provide functionality that is similar to the
Microsoft WinInet API. These classes provide varying levels of detail, from a
generic request/response model to control over application protocols and
sockets. In particular, the System.Net classes are designed for writing
scaleable, high-performance applications.
An application can use the System.Net classes to communicate with any other
application that supports the basic Internet protocols. However, that other
application need not be a .NET application. The .NET Framework provides
alternative mechanisms for inter-application communication.
For example, .NET Framework remoting implements a generic mechanism for
.NET Framework objects to interact with one another across application
domains. In addition, the System.Web.Services namespace contains classes for
applications to build and use XML Web services that are based on the standard
Simple Object Access Protocol (SOAP).
For more information about the remoting and XML Web services approaches to
inter-application communication, see Module 12, “Serialization,” in Course
2349B, Programming with the Microsoft .NET Framework (Microsoft
Visual C#
™
.NET).
After completing this module, you will be able to:
!
Use the basic request/response model to send and receive data over the
Internet.
!
Use the System.Net classes to communicate with other applications by
using the Hypertext Transfer Protocol (HTTP), Transmission Control
Protocol (TCP), User Datagram Protocol (UDP), and Socket Internet
protocols.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about the basic
request/response model that
is used to send and receive
data over the Internet, the
System.Net classes that
are used to communicate
with other applications, and
various techniques to
enhance application security
and performance.
2 Module 11: Internet Access
Internet Application Scenarios
!
Server-Side ASP.NET Applications
"
Obtain data from back-end sources for a browser
request
!
Peer-to-Peer Applications
"
Send and receive data by acting as servers and clients
!
Client Applications That Periodically Access the
Network
"
A robust implementation of HTTP 1.1, including:
Pipelining, chunking, authentication, pre-authentication,
encryption, proxy support, server certificate validation,
and connection management
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Several types of applications use the System.Net classes to send or receive data
over the Internet. The following three Internet application scenarios are
examples of Internet applications that use the System.Net classes:
!
Server-side ASP.NET applications that request data from server resources in
response to a browser request.
The System.Net classes are designed for writing scalable, high-performance
ASP.NET middle-tier applications. The server-side ASP.NET scenario
requires a robust middle-tier networking stack that can tolerate a high load.
The System.Net classes specifically fulfill this important customer
requirement. Such features as connection management, pipelining,
Keep-alive, and asynchronous operations ensure strong support for the
middle tier.
In addition, because the System.Net classes are part of an overall
framework, integration with ASP.NET features, such as impersonation and
caching, is seamless.
!
Peer-to-peer Windows Forms applications that act as servers and clients to
send and receive data.
!
Client applications that periodically access the network for updates.
The System.Net classes expose a robust implementation of the HTTP
protocol. Because a large share of Internet traffic travels over the HTTP
protocol, the protocol’s importance as an application protocol is significant.
The System.Net classes support most of the HTTP 1.1 protocol features.
The advanced features of HTTP 1.1 include pipelining, chunking,
authentication, pre-authentication, encryption, proxy support, server
certificate validation, connection management, and HTTP extensions.
Topic Objective
To introduce Internet
application scenarios that
use the System.Net
classes.
Lead-in
Several types of
applications use the
System.Net classes to send
or receive data over the
Internet.
Module 11: Internet Access 3
#
##
#
The WebRequest and WebResponse Model
!
Uniform Resource Identifier
!
NetworkStream Class
!
Creating a WebRequest
!
Invoking a WebRequest
!
Sending Data
!
Receiving Data
!
Using the WebRequest and WebResponse Model
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Internet applications can be classed broadly into two types: client applications
that request information, and server applications that respond to information
requests from clients. The classic Internet client/server application is the World
Wide Web, where people use browsers to access documents and other data that
is stored on Web servers worldwide.
Applications are not limited to playing either the client or server role; the
familiar middle-tier application server responds to requests from clients by
requesting data from another server. In this case, it is acting as both a server and
a client.
The client application makes a request by identifying the desired Internet
resource and the communication protocol that will be used to exchange the
request and response. If necessary, the client application also specifies any
additional data that is required to complete the request, such as proxy location
or authentication information. Authentication information includes such
information as user name and password. When the request is formed, it can be
sent to the server.
After the server has received the request and processed the response, the
response is returned to the client application. The response includes information
that supplements the contents of the response, such as the type of content,
which may include raw text or XML data.
Topic Objective
To introduce the topics in
the section.
Lead-in
Internet applications can be
classed broadly into two
types: client applications
that request information,
and server applications that
respond to information
requests from clients.
4 Module 11: Internet Access
The .NET Framework provides classes that can be used to implement a
request/response model to access Internet resources. The two principal classes
are the WebRequest class, which contains a request for the resource; and the
WebResponse class, which provides a container for the incoming response. In
addition, the Uri class is used to contain a Uniform Resource Identifier (URI),
which identifies the Internet resource that you are seeking. The
NetworkStream class is used to write and read the data.
A Uniform Resource Identifier URI is a compact representation of a
resource that is available to your application through the Internet. You may be
more familiar with the term, URL, which stands for Uniform Resource Locator.
URLs form a subset of the more general URI naming scheme. A URL identifies
an Internet resource that has a Web page address.
For applications that need to make simple requests for Internet resources, the
WebClient class provides common methods for uploading data to or
downloading data from an Internet server. WebClient relies on the
WebRequest class to provide access to Internet resources; therefore, the
WebClient class can use any registered pluggable protocol.
Note
Module 11: Internet Access 5
Uniform Resource Identifier
!
URI Contains:
"
Scheme identifier – specifies protocol to be used
"
Server identifier – specifies DNS name or TCP address
"
Path identifier – specifies location on the server
"
Optional query string – provides additional request information
!
Example: />"
Scheme identifier – http
"
Server identifier – www.contoso.com
"
Path identifier – /whatsnew.aspx
"
Query String – ?date=today
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The .NET Framework uses the URI to identify the desired communication
protocol and Internet resource.
The URI consists of at least three, and possibly four, parts:
!
The scheme identifier, which identifies the communications protocol that is
used by the request and response
!
The server identifier, which consists of a Domain Name System (DNS) host
name or TCP address that uniquely identifies the server on the Internet
!
The path identifier, which locates the requested information on the server
!
An optional query string, which passes information from the client to the
server
For example, the URI
consists of the scheme identifier http, the server identifier www.contoso.com,
the path identifier /whatsnew.aspx, and the query string ?date=today.
Topic Objective
To introduce the four parts
of the URI.
Lead-in
The .NET Framework uses
the URI to identify the
desired communication
protocol and Internet
resource.
6 Module 11: Internet Access
NetworkStream Class
!
A NetworkStream Object Provides:
"
A Way to Send and Receive All Types of Web Data
"
Methods That Are Compatible with Other .NET Streams
"
Processing of Data As It Arrives
!
System.Text.Encoding – Characters from and to Bytes
!
Sequential Blocks Use StreamReader and StreamWriter
// reading ASCII stream to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
// writing string to ASCII stream
Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);
// reading ASCII stream to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
// writing string to ASCII stream
Byte[] asciiBytes = Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
When resources on the Internet are obtained by using the System.Net classes, a
Stream object represents the data that is being sent and received.
Streams provide:
!
A common way to send and receive Web data.
Whether the actual contents of the file are HTML, XML, or another format,
an application uses Stream.Write and Stream.Read to send and receive
byte data.
!
Compatibility with streams across the .NET Framework.
Streams are used throughout the .NET Framework, which provides a rich
infrastructure for handling them. For example, by changing only the few
lines of code that initialize the stream, you can modify an application that
reads XML data from a file stream to read data from a network stream
instead.
The major differences between the NetworkStream class and other streams
are that the NetworkStream class is not seekable, the CanSeek property
always returns false, and the Seek and Position methods throw a
NotSupportedException.
!
Processing of data as it arrives.
Streams provide access to data as it arrives from the Internet, rather than
forcing your application to wait for an entire data set to be downloaded.
Topic Objective
To explain the function of
Network streams in the
.NET Framework.
Lead-in
When resources on the
Internet are obtained by
using the System.Net
classes, the data that is
being sent and received is
represented through a
Stream object.
Module 11: Internet Access 7
Conversion Between Characters and Bytes
The System.Text namespace contains classes for converting blocks of
characters to and from blocks of bytes. In particular, the Encoding class has
methods to convert arrays and strings of Unicode characters to and from arrays
of bytes, as in the following example:
// variable named anASCIIStream1 of type Stream
// has been previously assigned to a Stream
// containing bytes representing 7 bit ASCII character
//
// reading ASCII stream and converting to string
Byte[] read = new Byte[32];
int bytes = anASCIIStream1.Read(read, 0, read.Length);
string stringData = Encoding.ASCII.GetString(read);
//
// variable named anASCIIStream2 of type Stream
// has been previously assigned to a writable Stream
//
// converting string and writing 7 bit ASCII characters
Byte[] asciiBytes =
Encoding.ASCII.GetBytes(stringData);
anASCIIStream2.Write(asciiBytes, 0, asciiBytes.Length);
Converting Data from Sequential Blocks
When the data that must be converted is only available in sequential blocks,
such as data that is read from a long stream, an application may choose to use a
decoder or an encoder to perform the conversion. However, you can use the
StreamReader and StreamWriter classes to facilitate decoding and encoding
characters, as in the following example:
// variable anASCIIStream has been previously assigned
// to a Stream of ASCII bytes
StreamReader sr = new StreamReader(
anASCIIStream,Encoding.ASCII);
int length = 1024;
char[] Buffer = new char[1024];
int bytesread = 0;
//Read from the stream and write data to console
bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 ) {
Console.Write( Buffer,0, bytesread);
bytesread = sr.Read( Buffer, 0, length);
}
//Close the stream when finished
sr.Close();
8 Module 11: Internet Access
Creating a WebRequest
!
The WebRequest Encapsulates Details of Request
"
Created by calling WebRequest.Create method
"
Set any property values that are required
"
Cast to access protocol-specific features
WebRequest req =
WebRequest.Create(" />WebRequest req =
WebRequest.Create(" />HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create(" />// Turn off connection keep-alives.
httpReq.KeepAlive = false;
HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create(" />// Turn off connection keep-alives.
httpReq.KeepAlive = false;
req.Credentials = new
NetworkCredential("username","password");
req.Credentials = new
NetworkCredential("username","password");
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Client applications request data from servers by using the WebRequest class
and its descendents. The WebRequest class encapsulates the details of the
process of connecting to the server, sending the request, and receiving the
response.
Calling WebRequest.Create
Applications create WebRequest instances through the static
WebRequest.Create method. WebRequest.Create is a static method that
creates a descendent WebRequest instance that is based on the URI scheme
that is passed.
For example, the following code creates an HTTP request to
www.contoso.com:
WebRequest req =
WebRequest.Create("
Setting Required Property Values
Clients set required property values in the WebRequest instance. For example,
to support authentication, you can set the Credentials property to an instance of
the NetworkCredential class, as shown in the following code:
req.Credentials = new
NetworkCredential("username","password");
Topic Objective
To describe how client
applications use the
WebRequest.
Lead-in
Client applications request
data from servers by using
the WebRequest class and
its descendents.
Module 11: Internet Access 9
Casting WebRequest Objects to HttpWebRequest
To handle HTTP protocol requests to the Internet, the .NET Framework
provides an HttpWebRequest class that is derived from the WebRequest
class. In most cases, the WebRequest class provides all of the properties that
you need to make a request. However, if you need to access the HTTP
protocol-specific properties of the request, you can typecast WebRequest
objects that are created by the WebRequest.Create to HttpWebRequest, as in
the following example:
HttpWebRequest httpReq = (HttpWebRequest)
WebRequest.Create("
// Turn off connection keep-alives.
httpReq.KeepAlive = false;
Supporting Additional Protocols
The .NET Framework provides protocol-specific WebRequest and
WebResponse descendants for URIs that begin with http:, https:, and file:.
The programmable pluggable protocols of System.Net allow applications to
provide access through other protocols. To support additional protocols, you
should implement protocol-specific descendants of WebRequest and
WebResponse and register the descendant’s constructor with the
WebRequest.RegisterPrefix method.
For more information about supporting additional protocols, see the .NET
Framework Software Development Kit (SDK) documentation.
10 Module 11: Internet Access
Invoking a WebRequest
!
Request Is Made by Calling the GetResponse Method
"
Cast to access HTTP-specific features
WebResponse resp = req.GetResponse();
WebResponse resp = req.GetResponse();
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();
//Get the HTTP content length returned by the server.
String contentLength =
httpResp.ContentLength.ToString();
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();
//Get the HTTP content length returned by the server.
String contentLength =
httpResp.ContentLength.ToString();
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
After creating the WebRequest, you invoke the request for the Internet
resource by calling the GetResponse method on the WebRequest instance.
The GetResponse method is responsible for:
!
Constructing the protocol-specific request from the properties of the
WebRequest instance.
!
Making the TCP or UDP socket connection to the server.
!
Sending the request.
The GetResponse method returns an instance that is derived from
WebResponse that matches the instance that is derived from WebRequest, as
in the following example:
WebResponse resp = req.GetResponse();
The WebResponse class is also an abstract class that defines properties and
methods that are available to all applications that use pluggable protocols.
WebResponse descendents are responsible for implementing these properties
and methods for the underlying protocol.
For example, the HttpWebResponse class implements the WebResponse class
for the HTTP protocol. If you need to access the HTTP protocol-specific
properties of the response, you can typecast WebResponse objects to
HttpWebResponse, as in the following example:
HttpWebResponse httpResp =
(HttpWebResponse)httpReq.GetResponse();
//Get the HTTP content length returned by the server.
String contentLength = httpResp.ContentLength.ToString();
Topic Objective
To explain how to invoke the
request for an Internet
resource by calling the
GetResponse method on
the WebRequest instance.
Lead-in
After creating the
WebRequest, you invoke
the request for the Internet
resource by calling the
GetResponse method on
the WebRequest instance.
Module 11: Internet Access 11
Sending Data
!
For Requests That Send Data to the Server
//
try
{
byte[] sendData =
Encoding.ASCII.GetBytes("some data");
int sendLength = sendData.Length;
HttpWebRequest httpReq =
(HttpWebRequest) WebRequest.Create(
" />httpReq.Method = "POST";
httpReq.ContentLength = sendLength;
Stream sendStream = httpReq.GetRequestStream();
sendStream.Write(sendData,0,sendLength);
sendStream.Close();
}
catch(Exception e) {// } //
//
try
{
byte[] sendData =
Encoding.ASCII.GetBytes("some data");
int sendLength = sendData.Length;
HttpWebRequest httpReq =
(HttpWebRequest) WebRequest.Create(
" />httpReq.Method = "POST";
httpReq.ContentLength = sendLength;
Stream sendStream = httpReq.GetRequestStream();
sendStream.Write(sendData,0,sendLength);
sendStream.Close();
}
catch(Exception e) {// } //
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
For requests that send data to the server, such as HTTP-POST or FTP-PUT
requests, the data is sent through a network stream that is provided by the
WebRequest.GetRequestStream method. You use the resulting Stream
object to write the data. When you have finished uploading, you must close the
request stream with the Stream.Close method.
The following example shows how to create a request that uses HTTP-POST to
send data to the server:
//
try
{
byte[] sendData = Encoding.ASCII.GetBytes("some data");
int sendLength = sendData.Length;
HttpWebRequest httpReq =
(HttpWebRequest) WebRequest.Create(
"
httpReq.Method = "POST";
httpReq.ContentLength = sendLength;
Stream sendStream = httpReq.GetRequestStream();
sendStream.Write(sendData,0,sendLength);
sendStream.Close();
}
catch(Exception e)
{//
}
//
After closing the stream, you can call GetResponse to ensure that the server
received the data correctly.
Topic Objective
To describe how requests
that send data to the server
are created.
Lead-in
For requests that send data
to the server, such as
HTTP-POST or FTP-PUT
requests, the data is sent
through a network stream
that is provided by the
WebRequest.GetRequest
Stream method.
12 Module 11: Internet Access
Receiving Data
!
Reading Response Data
// Get the response stream.
Stream respstrm = resp.GetResponseStream();
// Create a buffer to hold the response data.
int BufferSize = 512;
Byte[] Buffer = new Byte[BufferSize];
// Read the stream to access the data.
int bytesRead = respstrm.Read(Buffer, 0, BufferSize);
while (bytesRead > 0) {
Console.Write(
Encoding.ASCII.GetString(Buffer, 0, bytesRead));
bytesRead = respstrm.Read(Buffer, 0, BufferSize);
}
respstrm.Close();
// Get the response stream.
Stream respstrm = resp.GetResponseStream();
// Create a buffer to hold the response data.
int BufferSize = 512;
Byte[] Buffer = new Byte[BufferSize];
// Read the stream to access the data.
int bytesRead = respstrm.Read(Buffer, 0, BufferSize);
while (bytesRead > 0) {
Console.Write(
Encoding.ASCII.GetString(Buffer, 0, bytesRead));
bytesRead = respstrm.Read(Buffer, 0, BufferSize);
}
respstrm.Close();
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
To obtain the stream that contains response data from the network resource, use
the GetResponseStream method of the WebResponse instance, as in the
following example:
// Get the response stream.
Stream respstrm = resp.GetResponseStream();
// Create a buffer to hold the response data.
int BufferSize = 512;
Byte[] Buffer = new Byte[BufferSize];
// Read the stream to access the data.
int bytesRead = respstrm.Read(Buffer, 0, BufferSize);
while (bytesRead > 0) {
Console.Write(
Encoding.ASCII.GetString(Buffer, 0, bytesRead));
bytesRead = respstrm.Read(Buffer, 0, BufferSize);
}
respstrm.Close();
If your application requires only the header information that is returned in the
WebResponse and ignores any returned data, then you do not need to get the
response stream.
Closing Responses
After reading the data from the response, you must close any opened stream by
using the Stream.Close method or close the response by using the
WebResponse.Close method, as in the following example:
resp.Close();
Topic Objective
To explain how to obtain the
stream that contains
response data from the
network.
Lead-in
To obtain the stream that
contains response data from
the network resource, use
the GetResponseStream
method of the
WebResponse instance.
Module 11: Internet Access 13
You do not have to call the Close method on both the response stream and the
WebResponse instance, but it is recommended. WebResponse.Close calls
Stream.Close when it closes the response. If you do not close each response,
your application will run out of connections to the server and be unable to
process additional requests.
Considerations for Working with NetworkStreams
When using streams from network resources, remember the following:
!
Because the NetworkStream class cannot change position in the stream, the
CanSeek property always returns false. The Seek and Position methods
throw a NotSupportedException.
!
When you use WebRequest and WebResponse, stream instances that are
created by calling GetResponseStream are read-only, and stream instances
that are created by calling GetRequestStream are write-only.
!
The call to GetResponse may block if network resources are not available.
You should consider using an asynchronous request with the
BeginGetResponse and EndGetResponse methods.
!
The call to GetRequestStream may block while the connection to the
server is created.
You should consider using an asynchronous request for the stream with the
BeginGetRequestStream and EndGetRequestStream methods.
Asynchronous operations are beyond the scope of this course.
!
You can use the StreamReader class to make the task of encoding easier.
The following code example uses a StreamReader to read an ASCII-
encoded stream from a WebResponse instance. The creation of the request
is not shown.
// Create a response object.
WebResponse response = request.GetResponse();
// Get a readable stream from the server.
StreamReader sr =
new StreamReader(
response.GetResponseStream(), Encoding.ASCII);
// Use the stream. Remember when you are through
// with the stream to close it
//
sr.Close();
14 Module 11: Internet Access
Using the WebRequest and WebResponse Model
//
WebRequest wReq = WebRequest.Create
("http://localhost/postinfo.html");
WebResponse wResp = wReq.GetResponse();
// Get a readable stream from the server
StreamReader sr = new StreamReader(
wResp.GetResponseStream(),Encoding.ASCII);
int length = 1024;
char[] Buffer = new char[1024];
int bytesread = 0;
//Read from the stream and write data to console
bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 ) {
Console.Write( Buffer,0, bytesread);
bytesread = sr.Read( Buffer, 0, length);
}
//Close the stream when finished
sr.Close();
//
//
WebRequest wReq = WebRequest.Create
("http://localhost/postinfo.html");
WebResponse wResp = wReq.GetResponse();
// Get a readable stream from the server
StreamReader sr = new StreamReader(
wResp.GetResponseStream(),Encoding.ASCII);
int length = 1024;
char[] Buffer = new char[1024];
int bytesread = 0;
//Read from the stream and write data to console
bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 ) {
Console.Write( Buffer,0, bytesread);
bytesread = sr.Read( Buffer, 0, length);
}
//Close the stream when finished
sr.Close();
//
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The following code example fully demonstrates the use of the WebRequest
and WebResponse model as discussed in this section:
using System;
using System.Net;
using System.IO;
using System.Text;
class App
{
public static void Main(string[] args)
{
try
{
WebRequest wReq = WebRequest.Create
("http://localhost/postinfo.html");
WebResponse wResp = wReq.GetResponse();
// Get a readable stream from the server
StreamReader sr = new StreamReader(
wResp.GetResponseStream(),Encoding.ASCII);
int length = 1024;
char[] Buffer = new char[1024];
int bytesread = 0;
(Code continued on the following page.)
Topic Objective
To provide an example of
the WebRequest and
WebResponse model.
Lead-in
You will now see an
example of the use of the
WebRequest and
WebResponse model as
discussed in this section.
Module 11: Internet Access 15
//Read from the stream and write data to console
bytesread = sr.Read( Buffer, 0, length);
while( bytesread > 0 )
{
Console.Write( Buffer,0, bytesread);
bytesread = sr.Read( Buffer, 0, length);
}
//Close the stream when finished
sr.Close();
}
catch(Exception e)
{
Console.WriteLine(
"\r\nThe request URI could not be found or was!
malformed:\n {0}",
e.ToString());
}
}
}
16 Module 11: Internet Access
#
##
#
Application Protocols
!
HTTP
!
Internet Domain Name System
!
TCP and UDP
!
Sockets
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The .NET Framework supports application protocols that are currently in
common use on the Internet.
This section provides information about using the HTTP, TCP, and UDP
protocol support that is provided in the .NET Framework, in addition to
information about using the Windows Sockets interface to implement custom
protocols.
Topic Objective
To introduce the topics in
the section.
Lead-in
The .NET Framework
supports application
protocols that are currently
in common use on the
Internet.
Module 11: Internet Access 17
HTTP
!
Classes That Provide HTTP and HTTPS Protocols
"
HttpWebRequest and HttpWebResponse
!
Support Most HTTP 1.1 features
!
HTTP Redirects Automatically if AllowAutoRedirect
Property Is true (the Default)
!
Use ServicePoint, ServicePointManager, and
ConnectionGroupName Classes to Manage Connections
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
With the HttpWebRequest and HttpWebResponse classes, the .NET
Framework provides comprehensive support for the HTTP protocol, which
makes up the majority of all Internet traffic.
Classes for the HTTP and HTTPS Protocols
The HttpWebRequest and HttpWebResponse classes are derived from the
WebRequest and WebResponse classes, as was described in Creating a
WebRequest in this module. HttpWebRequest and HttpWebResponse are
returned by default whenever the static method WebRequest.Create
encounters a URI that begins with http or https.
In most cases, the WebRequest and WebResponse classes provide all that is
necessary to make the request, but if you need access to the HTTP-specific
features that are exposed as properties, you can typecast these classes to
HttpWebRequest or HttpWebResponse, as demonstrated in Creating a
WebRequest in this module.
Do not use the HttpWebRequest constructor. Use the
WebRequest.Create method to initialize new HttpWebRequest instances. If
the scheme for the URI is
http://
or
https://
, Create returns an
HttpWebRequest instance.
Support for HTTP 1.1 Features
The HttpWebRequest and HttpWebResponse classes encapsulate a standard
HTTP request/response transaction and provide access to common HTTP
headers. These classes also support most HTTP 1.1 features, including
pipelining, chunking, authentication, pre-authentication, encryption, proxy
support, server certificate validation, and connection management. Custom
headers and headers that are not provided through properties can be stored in
and accessed through the Headers property.
Topic Objective
To describe the support that
the .NET Framework
provides for the HTTP
protocol.
Lead-in
With the HttpWebRequest
and HttpWebResponse
classes, the .NET
Framework provides
comprehensive support for
the HTTP protocol, which
makes up the majority of all
Internet traffic.
Note
18 Module 11: Internet Access
Support for HTTP Redirects
You can make your application follow HTTP redirects automatically by setting
the AllowAutoRedirect property to true, which is the default value. The
application redirects requests, and the ResponseURI property of
HttpWebResponse contains the actual Internet resource that responds to the
request. If you set AllowAutoRedirect to false, your application must be able
to handle redirects as HTTP protocol errors.
Applications receive HTTP protocol errors by catching a WebException with
the value of the Status property set to WebExceptionStatus.ProtocolError.
The Response property contains the WebResponse that is sent by the server
and indicates the actual HTTP error that is encountered.
Managing Internet Connections
Applications that use HTTP to connect to data resources can use the .NET
Framework ServicePoint and ServicePointManager classes to manage the
number of connections to the Internet and to optimize scale and performance.
The number of connections between a client and server can have a dramatic
effect on application throughput.
You can use ConnectionGroupName to form connection grouping that
associates specific requests within a single application to a defined connection
pool. You may have to use this technique with a middle-tier application that
connects to a back-end server on behalf of a user and uses an authentication
protocol that supports delegation, such as Kerberos, or by a middle-tier
application that supplies its own credentials.
For more information about classes that are used to manage connections and
their methods, see the .NET Framework SDK documentation.
Module 11: Internet Access 19
Internet Domain Name System
!
Dns Class Retrieves Data About a Host from DNS
"
GetHostByName query for www.contoso.com
"
Resolve query for www.contoso.com
IPHostEntry hostInfo =
Dns.GetHostByName("www.contoso.com");
IPHostEntry hostInfo =
Dns.GetHostByName("www.contoso.com");
IPHostEntry hostInfo =
Dns.Resolve("www.contoso.com");
IPHostEntry hostInfo =
Dns.Resolve("www.contoso.com");
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
The Dns class is a static class that retrieves information about a specific host
from the Internet Domain Name System (DNS).
The host information from a GetHostByName query is returned in an instance
of the IPHostEntry class. If the specified host has more than one entry in the
DNS database, IPHostEntry contains multiple Internet Protocol (IP) addresses
and aliases.
The following example queries the DNS database for information about a host
that is called www.contoso.com:
IPHostEntry hostInfo = Dns.GetHostByName("www.contoso.com");
The Resolve method queries a DNS server for the IP address that is associated
with a host name, such as www.contoso.com, or for an IP address in
dotted-quad notation, such as 192.168.1.2.
When the host name is a DNS-style host name that is associated with multiple
IP addresses, only the first IP address that resolves to that host name is returned,
as in the following example:
IPHostEntry hostInfo = Dns.Resolve("www.contoso.com");
Topic Objective
To explain how to use the
Dns class to retrieve
information about a host.
Lead-in
The Dns class is a static
class that retrieves
information about a specific
host from the Internet
Domain Name System.
20 Module 11: Internet Access
TCP and UDP
!
TCP Client Connecting to a Server/Listener
!
TCP Server/Listener Monitors Port for Clients
TcpClient tcpc = new TcpClient(serverURI, 14);
Stream s = tcpc.GetStream();
Byte[] read = new Byte[32];
int bytes = s.Read(read, 0, read.Length);
String strInData = Encoding.ASCII.GetString(read);
TcpClient tcpc = new TcpClient(serverURI, 14);
Stream s = tcpc.GetStream();
Byte[] read = new Byte[32];
int bytes = s.Read(read, 0, read.Length);
String strInData = Encoding.ASCII.GetString(read);
TcpListener tcpl = new TcpListener(14);
tcpl.Start();
while (!done) {
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
//Code to handle request goes here
}
tcpl.Stop();
TcpListener tcpl = new TcpListener(14);
tcpl.Start();
while (!done) {
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
//Code to handle request goes here
}
tcpl.Stop();
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Applications can use TCP and UDP services with the TcpClient, TcpListener,
and UdpClient classes. These classes, which are built on top of the Socket
class, represent the data that is sent and received from the network as streams.
These classes also take care of the details of creating a connection.
Using the TcpClient Class
You use the TcpClient class to request data from an Internet resource that uses
TCP. The methods and properties of TcpClient abstract the details for creating
a Socket instance that requests and receives data through TCP. The connection
to the Internet is represented as a stream; therefore data can be read and written
in a standard manner.
The following code demonstrates how to set up a TcpClient object to connect
to a server on TCP port 14:
TcpClient tcpc = new TcpClient(serverURI, 14);
Stream s = tcpc.GetStream();
Byte[] read = new Byte[32];
int bytes = s.Read(read, 0, read.Length);
String strInData = Encoding.ASCII.GetString(read);
Topic Objective
To explain how to use the
TcpClient and TcpListener
classes to request data from
an Internet resource and to
monitor TCP ports.
Lead-in
Applications can use TCP
and UDP services with the
TcpClient, TcpListener,
and UdpClient classes.
Module 11: Internet Access 21
Using the TcpListener Class
You use a TcpListener object to monitor a TCP port for incoming requests and
then create a Socket instance that manages the connection to the client. The
Start method enables listening, and the Stop method disables listening on the
port. The AcceptSocket method accepts incoming connection requests and
creates the socket that will handle the request.
The following code demonstrates how to set up a TcpListener object to
monitor TCP port 14:
TcpListener tcpl = new TcpListener(14); // listen on port 14
tcpl.Start();
while (!done) {
// Accept will block until someone connects
Socket s = tcpl.AcceptSocket();
//Code to handle request goes here
}
tcpl.Stop();