Web Streams
Rather than reading from a stream provided by a custom server, you can just as easily read from any web page on the Internet.
A WebRequest
is an object that requests a
Uniform Resource Identifier (URI)
such as the URL for a web page. You can use a
WebRequest
object to create a
WebResponse
object that will encapsulate the
object pointed to by the URI. That is, you can call
GetResponse( )
on your WebRequest
object to get the actual object (e.g., a web page) pointed to by the
URI. What you get back is encapsulated in a
WebResponse
object. You can then ask that
WebResponse
object for a Stream
object by calling GetResponseStream()
.
GetResponseStream( )
returns a stream that
encapsulates the contents of the web object (e.g., a stream with the
web page).
The next example retrieves the contents of a web page as a stream. To
get a web page, you’ll want to use
HttpWebRequest
. HttpWebRequest
derives from WebRequest
and provides additional
support for interacting with the HTTP protocol.
To create the HttpWebRequest
you cast the
WebRequest
returned from the static
Create( )
method of the
WebRequestFactory
:
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create ("http://www.libertyassociates.com/book_edit.htm");
Create( )
is a static method of
WebRequest
. When you pass in a URI, an instance of
HTTPWebRequest
is created.
Tip
The method is overloaded on the type of the parameter. It returns different derived types depending on what is passed in. For example, if you pass in ...
Get Programming C# now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.