Retrieving HTTP Content In .NET

xiaoxiao2021-03-19  200

Retrieving HTTP Content In .NET

BY

Rick Strahl

West Wind Technologies

http://www.west-wind.com/

Last Update:

March 12, 2002

Code for this article:

http://www.west-wind.com/pesentations/dotNetWebRequest/dotNetWebRequest.zip

Sidebars:

http://www.west-wind.com/pesentations/dotNetWebRequest/dotNetWebRequest_sidebars.htm

HTTP content retrieval is an important component for applications these days. Although .NET reduces the need to explicitly retrieve content from the Web through built-in mechanisms in the Web Services framework, ADO.NET and the XML classes, there are still many needs to retrieve Web content directly and manipulate it as text or data downloaded into files. In this article Rick describes the functionality of the HttpWebRequest and HttpWebResponse classes and provides an easy to use wrapper class. The class simplifies the HTTP access and provides most of the common features in an easy to use single interface while still providing full access to the base functionality of the HttpWebRequest class. in the process Rick describes some sticky issues like string encoding and Cookie handling and some related topics like implementing events and running multiple threads to service Web requests .

Last week I decided I needed a good, useful project to throw at .NET to continue my learning curve while actually building something I have a use for. A few years back I'd written a Web Monitoring package that allows me to monitor a set of Web sites and send out alerts when the sites are down and not responding. The app has been showing its age and since it was developed using C it has a clunky user interface that's not very maintainable. I thought this would be a good 'training 'application to re-build for .NET. This application exercises HTTP functionality built into the .NET Framework, requires setting up and running multiple threads, hooking up events and managing a small set of data without a database backend and finally providing a Windows Form UI. In the future converting this application to work as a Windows service would also be a nice feature. This application is one that lets me explore a wide variety of features of a programming environment. In this month's article I'll d Escribe a few of the features That I Needed to build focusing specification ion the http retrieval mechanism.new http Tools in .net

The .NET Framework provides new tools for retrieving HTTP content that are powerful and scalable in a single package. If you've ever worked in pre-.NET applications and tried to retrieve HTTP content you probably know that there are a number of different tools available:.. WinInet (Win32 API), XMLHTTP (part of MSXML) and recently the new WinHTTP COM library These tools invariably all worked in some situations, but none of them really fit the bill for all instances for example, WinInet can not scale on the server with no multi-threading support. XMLHTTP was too simple and did not support all aspects of the HTTP model. WinHTTP which is the latest Microsoft tool for COM solves many of these problems but it does not work at all on Win9x, which makes it a bad choice for a client tool integrated into broad distribution apps at least for the moment until XP take a strong hold.The.NET framework greatly simplifies HTTP access with a pair of classes HttpWebRequest and HttpWebResponse. These classes Provide Just About All of the FunctionAncol in A StraightForward Manner. The Basics of Returning Content from the Web Requires Very Little Code (See Listing 1).

Listing 1: Simple Retrieval of Web Data Over HTTP.

String lcurl = "http://www.west-wind.com/testpage.wwd";

// *** Establish The Request

Httpwebrequest lohttp =

(Httpwebrequest) WebRequest.create (LCURL);

// *** Set Properties

Lohttp.timeout = 10000; // 10 SECS

Lohttp.Userage = "code sample web client";

// *** Retrieve Request Info Headers

HttpWebResponse LoweBRESPONSE = (httpwebresponse) Lohttp.getResponse ();

Encoding enc = encoding.getencoding (1252); // windows default code pagestreamReader loresponsestream =

New streamreader (LoweBRESPONSE.GETRESPONSSTREAM (), ENC);

String lchtml = loresponsestream.readtoend ();

LowebResponse.close ();

LoResponsestream.close ();

PRETTY SIMPLE, RIGHT? But Beneath This Simplicity Lies a Lot of Power Too. Let's Start with Looking At How this Works.

Start by creating the HttpWebRequest object which is the base object used to initiate a Web request. A call to the static WebRequest.Create () method is used to parse the URL and pass the resolved URL into the request object. This call will throw an Exception if The Url Passed Has Invalid Url Syntax.

The request portion controls how the outbound HTTP request is structured. As such it handles configuration of the HTTP headers, the most common of which are expressed as properties of the HttpWebRequest object. A few examples are UserAgent, ContentType, Expires and even a Cookies collection which map directly to header values ​​that get set when the response is sent. headers can also be set explicitly using the headers string collection to which you can add either a whole header string or a key value pair. Generally the properties address all common headers, SO You'll Rarely Need To Resort To Setting Headers Explicitly Most LIKELY ONLY To Support Special Protocols (for Example, SOAPAAPATION for SOAP Requests).

In the example, I do nothing much with the request other than setting a couple of the optional properties -. The UserAgent (the client 'browser' which is blank otherwise) and the Timeout for the request If you need to POST data to the server You'll Need to Do a Little More Work - I'll Talk About this a little latern.streaming good deals

Once the HTTP Request is configured for sending the data, a call to GetResponse () actually goes out and sends the HTTP request to the Web Server. At this point the request sends the headers and retrieves the first HTTP result buffer from the Web Server.

When the code above performs the GetResponse () call only a small chunk of data is returned from the Web server. The first chunk contains the HTTP header and the very first part of the data, which is simply buffered internally until read from the stream itself .................. ..

Next a stream is returned using the GetResponseStream () method. The stream points at the actual binary HTTP response from the Web server. Streams give you a lot of flexibility in handling how data is retriveved from the web server (see Streams and StreamReader sidebar) . ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

In the example above I use a StreamReader object to return a string from the data in a single operation. But realize that because a stream is returned I could access the stream directly and read smaller chunks to say provide status information on progress of the HTTP download .Notice also that when the StreamReader is created I had to explicitly provide an encoding type - in this case codePage 1252 which is the Windows default codepage This is important because the data is transferred as a byte stream and without the encoding it would result in. .. invalid character translations for any extended characters CodePage 1252 works fairly well for English or European language content, as well as binary content Ideally though you will need to decide at runtime which encoding to use - for example a binary file probably should write a stream Out to File or other location rather Than Converting to a string, while a page from japan surunding for That Language. (for More Information See The Encoding Sidebar.

I use the StreamReader object which provides an easy mechanism to retrieve the contents of a stream into strings or arrays of characters. It also provides the handy ReadToEnd () method which retrieves the entire stream in a single batch. The operation of reading the stream is what actually retrieves the data from the Web server (except for the initial block that was read to retrieve the headers). In this case a single read operation is called and retrieves the data with the request blocking until the data has been returned. If you wanted to provide feedback you can also read the data in chunks using the StreamReader's Read () method which lets you specify the size of the data to read. you'd run this in a loop and provide whatever status info you need on each read. with this mechanism you can retrieve the data and provide progress information.StreamReader also exposes the underlying raw stream using the BaseStream property, so StreamReader is a good object to use to pass streamed data aro Und.

Posting data

The example above only retrieves data which is essentially an HTTP GET request. If you want to send data to the server you can use an HTTP POST operation. POSTing data refers to the process of taking data and sending it to the Web server as part of The Request PayLoad. a Post Operation Both Sends Data To The Server and Retrieves A Response.

Posting Uses a stream to send the data to the server, so the process of posting data is pretty much the reverse of retrieving the data (see Listing 2).

Listing 2: Posting Data To The Web Server

String lcurl = "http://www.west-wind.com/testpage.wwd";

Httpwebrequest lohttp =

(Httpwebrequest) WebRequest.create (LCURL);

// *** Send Any Post Data

String lcpostdata = "name =" httputility.urlencode ("

Rick Strahl

")

"& Company =" httputility.urlencode ("West Wind");

Lohttp.method = "pos";

BYTE [] lbpostbuffer = system.text.

Encoding.getencoding (1252) .getbytes (LcPostData);

Lohttp.contentLength = lbpostbuffer.length;

Stream lopostdata = Lohttp.getRequestStream ();

LopostData.write (lbpostbuffer, 0, lbpostbuffer.length);

LopostData.Close ();

HttpWebResponse LoweBRESPONSE = (httpwebresponse) Lohttp.getResponse ();

Encoding enc = system.text.encoding.getencoding (1252);

StreamReader loresponsestream =

New streamreader (LoweBRESPONSE.GETRESPONSSTREAM (), ENC);

String lchtml = loresponsestream.readtoend ();

LowebResponse.close ();

LoResponsestream.close ();

Make sure you use the this POST code immediately before the HttpWebRequest.GetResponse () call. All other manipulation of the Request object has no effect as the headers get send with the POST buffer. The rest of the code is identical to what was shown before - You Retrieve The Response and The Read The Stream To Grab The Result Data.

POST data needs to be properly encoded when sent to the server. If you're posting information to a Web page you'll have to make sure to properly encode your POST buffer into key value pairs and using URLEncoding for the values. You can utilize .. the static method System.Web.HttpUtility.UrlEncode () to encode the data in this case make sure to include the System.Web namespace in your project Note this is necessary only if you're posting to a typical HTML page - if you're posting XML or other application content you can just post the raw data as is. This is all much easier to do using a custom class like the one included with this article. This class has an AddPostKey method and depending on the POST mode IT WILL Take Any Parameters and protly encode The Into an internally manage stream which is the posted to the server.

To send the actual data in the POST buffer the data has to be converted to a byte array first. Again we need to properly encode the string. Using Encoding.GetEncoding (1252) encoding with the GetBytes () method which returns a byte array using the Windows standard ANSI code page. you should then set the ContentLength property so the server can know the size of the data stream coming in. Finally you can write the POST data to the server using an output stream returned from HttpWebRequest.GetRequestStream (). Simply write the entire byte array out to the stream in one Write () method call with the appropriate size of the byte array. This writes the data and waits for completion. As with the retrieval operation the stream operations are what actually causes data to be Sent to the Server SO if you want to provide progress information you can send smaller chunks and provide feedback to the user if needed.beyond the Basics

. The basic operation of using HttpWebRequest / HttpWebResponse is straight forward But if you build typical applications that use HTTP access quite a bit you'll find that you'll have to set a number of additional properties; object properties in particular One nice feature. Of the .NET Framework is The Consistency of Common Objects Being Reuse for Many Areas of The Framework.

If you use Authentication in your ASP.NET applications the objects used on the server have the same interface as they do on the client side. In this section I'll address the topics of Authentication, Proxy configuration and using Cookies which are a few things that you probably will have to do as part of installing HttpWebRequest as a client solution. All three of these objects used by HttpWebRequest / Response are standard objects that you'll find in other places of the framework.Authentication

Logging into Web content is very common for distributed applications as a security measure. Web authentication typically consists of either Basic Authentication (which is application driven prompting for an operating system account usually) or NTLM (integrated file security).

To Authenticate a User You Use The Credentials Property:

WebRequest.credentials = New NetworkCredential ("UserName", "Password");

If you're using Basic Authentication only the username and password are meaningful while with NTLM you can also pass a domain name. If you're authenticating against an NTLM resource (permissions set on the server's file system) from a Windows client application, you Can Also Use The Currently Logged On User's Credentials Like this:

WebRequest.credentials = CredentialCache.defaultcredentials;

HttpWebRequest handles navigation of the Authentication HTTP protocol requests so an authenticated request operates like any other if it validates. If the request fails due to authentication an exception is thrown.

Proxy Server Configuration

If you want to build a solid Web front end into a client application you will have to deal with clients that sit behind a firewall / proxy and you're application will have to handle these settings. Luckily HttpWebRequest makes this fairly painless with a WebProxy class MEMBER THAT TAKES The Information. To configure a proxy you can users: // pass proxy string and bypass local machine

WebProxy loProxy = new webproxy ("http://proxy-server.mine.com:8080", true);

// ** bypasslist

String [] CBYPASS = New String [2];

CBypass [1] = "http://someserver.net";

Cbypass [2] = http://192.0.0.1

Loproxy.bypasslist = cbypass;

// ** Proxy Authentication

Loproxy.credentials = New NetworkCredential ("proxyusername", "pass");

Request.proxy = loproxy;

How much detail is provided to the Proxy object depends on the particular Proxy server. For example a bypass list is not required, and most proxies do not require a username and password in which case you do not need to provide the credentials.

WebProxy Can Also Cram All The Parameters Into The Constructor Like this:

Request.Proxy = new webproxy

"http://proxy-server.mine.com:8080" ,true ,cbypass ,new networkcredential (...);

HTTP Cookies

HTTP Cookies are a state management implementation of the HTTP protocol and many Web pages require them. If you're using remote HTTP functionality to drive a Web site (following URLs and the like) you will in many case have to be able to support cookies .

Cookies work by storing tokens on the client side, so the client side is really responsible for managing any cookie created. Normally a browser manages all of this for you, but here there's no browser to help out in an application front end and we're responsible for tracking this state ourselves. This means when the server assigns a cookie for one request, the client must hang on to it and send it back to the server on the next request where it applies (based on the Web site and virtual directory) . HttpWebRequest and HttpWebResponse provide the container to hold cookies both for the sending and receiving ends but it does not automatically persist them so that becomes your responsibility.Because the Cookie collections are nicely abstracted in these objects it's fairly easy to save and restore them. THE Key to make this work is to have a personistent object reference to the cookie collection and the reuse the same cookie store each time.

To do this let's assume you are running the request on a form (or some other class - this in the example ": you'd create a property called cookies:

Cookiecollection cookies;

On The Request End of The Connection Before The Request Is Sent To The Server You Can THEN CHECK WHENER The Server You CAN THEN CHETER THERE'S A Previously Saved Set of Cookies And if So Use Them:

Request.cookieContainer = new cookiecontainer ();

IF (this.cookies! = null&&

THIS.COOKIES.COUNT> 0)

Request.cookiecontainer.add (this.cookies);

So, if you previously had retrieved cookies, they were stored in the Cookies property and then added back into the Request's CookieContainer property CookieContainer is a collection of cookie collections -. It's meant to be able to store cookies for multiple sites Here I only deal. WITH TRACKING A SINGLE SET OF COKIES for a Single Set of Requests.on The Receiving End The Request Headers Have Been Retrieved After the Call To GetWebresponse () You Use Code Like The Following:

// *** save the cookies on the penistent object

IF (response.cookies.count> 0)

THIS.COOKIES = response.cookies;

This saves the cookies collection until the next request when it is then reassigned to the Request which sends it to the server. Note, that this is a very simplistic cookie management approach that will work only if a single or a single set of cookies is set .. on a given Web site If multiple cookies are set in multiple different places of the site you will actually have to retrieve the individual cookies and individually store them into the Cookie collection Here's some code that demonstrates:

IF (LowebResponse.cookies.count> 0)

IF (this.cookies == NULL)

{

THIS.COOKIES = LowebResponse.cookies;

}

Else

{

// if We Already Have Cookies Update List

Foreach (cookie orespcookie in

LowebResponse.cookies)

{

Bool bmatch = false;

Foreach (cookie Oreqikeie in)

THIS.OCOOKIES) {

IF (OreqCookie.name ==

Orespcookie.name) {

OreqCookie.Value =

Orespcookie.name;

BMATCH = TRUE;

Break;

}

}

IF (! bmatch)

This.cookies.Add (Orespcookie);

}

}

}

This should give you a good starting point. This code still does not deal with things like domains and virtual paths and also does not deal with saved cookies, but for most applications the above should be sufficient.Wrapping it up

By now you're probably getting an idea of ​​the power that is provided by the HttpWebRequest object. While using these objects is a straight forward process it does require a fair amount of code and, using these objects required a fair amount of code and knowledge OF A NUMBER OF CLASSES.

Since I use HTTP access in just about every application I create, I decided to create a wrapper class called wwHttp that simplifies the whole process quite a bit (the class is included in the code download for this article). Rather than creating two separate Request and Response objects the single class handles in a single object with simple string properties. The class handles setting up POST variables for you, creating any authentication and proxy settings from strings rather than objects, manages cookie and provides an optional simplified error handler that sets properties instead of throwing exceptions It does this while allowing access to the base objects -. you can pass in a WebRequest object and retrieve a reference to both the Request and Response objects, so you can get the best of both worlds with simplicity without giving up any Of the features of the framework classes. The Class Also Provides Several Overloaded Methods for Returning Strings, Streams and Running Output To Fi Le. The Class Can Be Set Up to Fire Events At Buffer Retrieval Points When Data IS Downloaded to Provide Feed Back In A Gui Application.

START by adding the name:

USING WestWind.Tools.http;

USING THE CLASS You CAN Retrieve Content from A Site As SIMPLY AS THIS: WWHTTP LOHTTP = New WWHTTP ();

Lohttp.username = "ricks";

Lohttp.password = "password";

Lohttp.proxyaddress = "http://proxy-server.hawaii.r.COM: 8080";

Lohttp.addpostKey ("name", "

Rick Strahl

");

Lohttp.addpostKey ("Company", "West Wind Technology");

Lohttp.handlecookies = true; // enable Automatic Tracking for 5 cookies

String lchtml = Lohttp.geturl ("http://www.west-wind.com/testpage.wwd");

Most of those property settings are optional but just about everything in the class is accessible with simple strings. AddPostKey () automates the creation of UrlEncoded strings. Several different POST modes are supported including UrlEncoded (0), Multi-Part (2) and raw XML (4) pos.

. A corresponding The GetUrl () methods has several different signatures You can pass in an optional WebRequest object that is preconfigured so if you need to set one of the to override some properties that are not exposed you can override them there For example.:

HttpWebRequest Oreq = (httpwebrequest) WebRequest.create (LCURL);

Oreq.expires = -1

Oreq.Headers.Add ("soapaction", "http://west-wind.com/soap#method");

WWHTTP REQUEST = New WWHTTP ();

String lchtml = request.geturl (OREQ);

WWHTTP Also Exposed Error and ErrorMsg Properties That Can Be Used To Quickly Check for Error Conditions:

LCHTML = Request.geturl (LCURL);

IF (Request.Error)

Messagebox.show (Request.ErrorMSG);

Else

THIS.TXTRESULT.TEXT = LCHTML;

Expllict Error Retrieval Is The Default, But You Can Use the ThrowExceptions Property To Have The Class Pass Forward Exceptions to your code.posting data

As I mentioned earlier POST data is important in Web request applications and getting the data into the proper format for posting can be tricky requiring possibly a fair amount of code. WwHttp abstracts the process with several overloads of the AddPostKey () method which handles the different POST MODES: 1 - Urlencoded Form Variables, 2 - Multi-Part Form Variables and Files, 4 - XML ​​or Raw Post Buffers.the base method Looks as shown in listing 3.

Listing 3: WWHTTP :: AddPostKey Handles Post Data

Public void addpostkey (String Key, Byte [] Value)

{

IF (this.opostdata == null)

{

This.opostStream = new memorystream ();

this.opostdata = new binarywriter (this.opostStream);

}

IF (key == "reset")

{

This.opostStream = new memorystream ();

this.opostdata = new binarywriter (this.opostStream);

}

Switch (this.npostmode)

{

Case 1:

This.opostData.write (Encoding.Getencoding (1252) .Getbytes

Key "="

System.Web.httputility.urlencode (Value) "&"));

Break;

Case 2:

This.opostData.write (Encoding.Getencoding (1252) .Getbytes

"-" this.cmultipartboundary "/ r / n"

"Content-Disposition: Form-Data; Name = /" " Key

"/" / r / n / r / n "))))

This.opostData.write (value);

This.opostData.write (Encoding.Getencoding (1252) .Getbytes ("/ r / n"));

Break;

DEFAULT:

This.opostData.write (value);

Break;

}

}

This method relies on a stream oPostStream to hold the cumulative POST data a user might send to the server. A BinaryWriter object is used to actually write to the stream sequentially without having to count bytes as you have to do with the raw stream.Next the actual POST data is actually written into the stream using the Write () of the BinaryWriter. Note that this version of AddPostKey () accepts a byte [] input parameter rather than a string so the data can be written in its raw format.

The BinaryWriter Write () method has overloads that allow for string parameters, however, this did not work correctly for me as the encoding was screwed up in the output. Instead the code above explicitly performs the translation for any strings (including static strings like the ones for the multipart form vars) from string to byte array, using the proper encoding as discussed previously. Once again, this was tricky to figure out as you can set an encoding on the BinaryWriter, but which did not appear to have any Effect. The Code Shown Above Was The Only Working Solution That Runs Correctly.

There Are Several Overloads to this method. Most Importantly is a string version:

Public Void AddPostKey (String Key, String Value)

{

THIS.AddPostKey (key, encoding.getencoding (1252) .getbytes (value));

}

Which Does Little More Than Converting The String Into A Byte Array with The Proper Encoding. Another Version Accepts a Single Post Buffer, Which is Typically Used for XML OR Binary Content.

Public void AddPostKey (String FullPostBuffer)

{

This.opostData.write (Encoding.Getencoding (1252) .Getbytes (fullpostbuffer);

}

This One Writes Directly to The Binary Writer.

Finally there's an AddPostFile () method which allows you to POST a file to the server when running with multi-part forms (PostMode = 2) to provide HTML file upload capabilities.Listing 3.1: HTTP file upload method for multi-part forms

Public Bool AddPostfile (String Key, String Filename)

{

LCFILE;

IF (this.npostmode! = 2) {

this.cerrormsg = "File Upload Allowed Only with Multi-Part Forms";

THIS.BERROR = True;

Return False;

}

Try

{

FileStream Lofile = New FileStream (filename, system.io.filemode.open,

System.IO.FileAccess.read;

Lcfile = New byte [Lofile.Length];

Lofile.read (lcfile, 0, (int) Lofile.Length);

Lofile.Close ();

}

Catch (Exception E)

{

THIS.CERRORMSG = E.MESSAGE;

THIS.BERROR = True;

Return False;

}

This.opostData.write (Encoding.Getencoding (1252) .Getbytes

"-" this.cmultipartboundary "/ r / n"

"Content-Disposition: Form-Data; Name = /" Key "/" filename = / ""

New fileInfo (filename) .Name "/" / r / n / r / n "))))

This.opostData.write (lcfile);

This.opostData.write (Encoding.Getencoding (1252) .Getbytes ("/ r / n"));

Return True;

}

............. ..

Listing 3.2: Sending the Post Data to the Server

// *** DEAL with the post buffer if any one

IF (this.opostdata! = null)

{

Request.Method = "post";

Switch (this.npostmode)

{

Case 1:

Request.contentType = "Application / X-WWW-FORM-URLENCODED";

Break;

Case 2:

Request.contentType = "Multipart / Form-data; boundary =" this.cmultipartboundary;

This.opostData.write (Encoding.Getencoding (1252) .Getbytes ("-"

this.cmultipartboundary "/ r / n"))));

Break;

Case 4:

Request.contentType = "text / xml";

Break;

DEFAULT:

Goto Case 1;

}

Stream lopostdata = request.getRequestStream ();

// *** Copy The Memory Stream To The Request Street

This.opostStream.writeto (LopostData);

// *** Close The Memory Stream

THIS.OPOSTREAM.CLOSE ();

THIS.OPOSTSTREAM = NULL;

// *** Close The Binary Writer

This.opostdata.close ();

THIS.OPOSTDATA = NULL;

// *** Close Request Stream

LopostData.Close ();

}

This code finalizes the request for POST data by checking whether we've already written something into the POST buffer and if so configuring the POST request by specifying the content type. In the case of multi-part form POST an epilogue string is added to the End of the content.

Writing out the data entails taking the data from the memory stream that holds our accumulated POST data and writing it out to the request stream (loPostData) which actually sends the POST data to the server.

As you can see a lot of things are happy in order...................

Firing Events

Other versions of the GetUrl () method return a StreamReader object and yet another version GetUrlEvents () that fires an OnReceiveData event whenever data arrives in the buffer. The event provides a current byte and total byte count (if available) as well as two flags DONE AND Cancel. Done lets you know, while the Cancel flag lets your code stop Download Data.to Run with the Event Enabled You Just Hook Up An Event Handler To The Event:

Httpwebrequest lohttp = new wwhttp ();

Lohttp.onreceiveData = New

WWHTTP.ONRECEIVEDATAHANDAL (this.lohttp_onreceivedata);

String lchtml = lohttp.geturlevents (this.txtURL.Text.trimend (), 4096);

THIS.TXTHTML.TEXT = LCHTML;

Lohttp.onreceiveData - =

New WWHTTP.ONRECEIVEDATAHANDLER

THISLOHTTP_ONRECEIVEDATA);

Make sure to disconnect the handler at the end of your request, or set it up in a static location that runs only one time. The event handler method can then do some work with the data in the OnReceiveDataArgs obhect returned to you (Listing 3) :

Listing 4: Implementing The WWHTTP :: OnRecEiveData Event

Private void Lohttp_onreceiveData (Object Sender,

WWHTTP.ONRECEIVEDATAEVENTARGS E) {

IF (e.done)

Messagebox.show ("Download Complete!");

Else IF (E.NUMBEROFREADS == 20) {

Messagebox.show ("Cancelling ... Too Large.");

e.cancel = true;

}

Else

this.Ostatus.Panels [0] .text =

E.CurrentBytecount.toString () "of"

e.totalbytes.toString () "Bytes Read";

}

Using the Event IS Easy. Creating The Event On The WWHTTP Class Is A Bit More Involved and Requires Three Steps:

First The Actual Event Needs to Be Defined On The Class:

Public Event OnReceiDataHandler OnReceiData; Next The Event's Arguments Need To Be Wrapped Up Into a Class Contains The Arguments As Properties:

Public Class OnRecEiveDataEventAeventAeventArgs

{

Public long currentBytecount = 0;

Public long Totalbytes = 0;

Public int numBerofreads = 0;

Public char [] Currentchunk;

Public bool done = false;

Public Bool Cancel = False;

}

Creating a public delegate Which Acts as the method Signature for the event to be called:

Public Delegate Void OnRecEiveDataHandler (Object Sender,

OnreceiveDataEventArgs E);

You only need to define this delegate if you want to pass custom parameters. If no parameters are required you can just define your event use the standard System.EventHandler delegate. These three pieces make up the event interface.

To actually fire the event you can simply run your code and call the call the function pointer that the user assigned to the event. Here's the relevant code from wwHttp that demonstrates how the Response loop is read and how the event is fired on each update cycle .

Listing 5: Reading The Response Street and Firing Events

StreamReader OHTTPRESPRESPONSE = this.geturlstream (URL);

IF (OHTTPRESPONSE == NULL)

""; "

Long lnsize = buffersize;

// *** Use stringbuilder to create the result string

Stringbuilder Lowriter = New StringBuilder ((int) lnsize);

// *** CREATE The Argument Structure Used As Event Parm

OnreceiveDataEventArgs OARGS = New OnreceiveDataEventAeventArgs ();

OARGS.TOTALBYTES = LNSIZE;

While (lnsize> 0) {

Lnsize = OHTTPRESPONSE.READ (lcTemp, 0, (int) buffersize;

IF (lnsize> 0)

{

Lowriter.Append (lcTemp, 0, (int) lnsize);

Lncount ;

LNTOTALBYTES = lnsize; // *** Raise An Event IF HOOKED UP

IF (this.onreceiveData! = null)

{

/// *** Update the Event Handler

OARGS.CURRENTBYTECUNT = lntotalbytes;

ORGS.NUMBEROFREADS = lncount;

OARGS.CURRENTCHUNK = LCTEMP;

// *** Call the Event Method

THIS.ONRECEIVEDATA (THIS, OARGS);

// *** Check for cancelled flag

IF (OARGS.CANCEL)

Goto closed;

}

}

} // while

The key to this code is the delegate OnReceiveData (see the Delegates Sidebar for more on delegates). It acts a function pointer which points the assigned method on the form in the example above. From within the stream reading loop this method is called every time A New Buffer is Retrieved.

We Can Walk and Chew Gum At the Same Time!

Events are cool, but they're not all that useful if you're running in blocking mode as I've shown so far. HttpWebRequest / HttpWebResponse can also be run in asynchronous modes using the BeginGetResponse / EndGetResponse methods. Most of the stream classes Provide this Mechanism Which Allows You to Specify A Callback Method To Collect Output Retrieved from these Requests (You Can Also Send Data Asynchronously this Way).

However, after playing with this for a while and then looking at the native thread support in the .NET framework it turned out to be easier to create a new thread of my own and encapsulate the thread operation in a class. The following example runs multiple wwHttp objects on a couple of threads simultaneously while also updating the form with information from the OnReceiveData event. Figure 1 shows what the form looks like. While the HTTP requests are retrieved the main form thread is still available to perform other tasks, so you can move around the form, so the form's UI remains active all the while.Figure 1 - this example form runs two HTTP requests simultaneously firing events that update the form's status fields While these requests run the form remains 'live'..

This process is surprisingly simple in .NET partly because .NET makes it easy to route thread methods into classes. This make it both easy to create a thread's processing into a nicely encapsulated format as well as providing an easy packaging mechanism for passing data into a Thread and keeping That data isolated from the rest of an application.

Make sure you add the System.Threading namespace to your forms that use threads. The following code defines the thread handler class that fires the HTTP request with the FireUrls () method (Listing 5).

Listing 6: IMPLEMENTING A THREAD CLASS

Public class getURLS

{

Public String Url = ""

Public WWHTTPMULTITITEAD PARENTFORM = NULL;

Public int instance = 1;

Public void fireurls ()

{

WWHTTP OHTTP = New WWHTTP ();

Ohttp.onreceiveData =

New WWHTTP.ONRECEIVEDATAHANDAL (this.onreceiveData);

Ohttp.timeout = 5;

String lchtml = OHTTP.GeturLevents (this.url, 4096); if (ohttp.error)

This.Parentform.lblResult.text = OHTTP.ErrorMsg;

}

Public void onRecEidData (Object Sender,

WWHTTP.ONRECEIVEDATAEVENTARGS E)

{

IF (this.instance == 1)

this.parentform.lblResult.text =

E.CurrentBytecount.toString () "Bytes";

Else

This.Parentform.lblResult2.text = E.currentbytecount.toString () "bytes";

}

}

There's nothing special about this class -. In fact any class would do as thread handler (as long as you write thread safe code) This simplified implementation includes a reference back to the ParentForm that makes it possible to access the status labels on the form. The Instance property is used to identify which request is updating which form control. The actual code here is very much like code I've previously shown using the wwHttp object. Note that this code assigns the event handler a method of the thread action class. This Method The Calls Back to the Parentform and Updates The Labels.

The Calling Code on The Form Creates Two Threads That Call The FireURLS Method As Follows (Listing 6):

Listing 7: Creating and Running the Thread

Private void cmdgo_click (Object Sender, System.Eventargs E)

{

GetURLS OGETURLS = New getURLS ();

Ogeturls.url = this.txtURL.Text;

Ogeturls.parentform = this;

ThreadStart Odelegate =

New ThreadStart (Ogeturls.fireURLS);

Thread mythread = new thread (ODELEGATE);

mythread.start ();

GetURLS OGETURLS2 = New getURLS ();

Ogeturls2.parentform = this;

Ogeturls2.url = this.txtURL2.TEXT;

Ogeturls2.instance = 2;

ThreadStart Odelegate2 =

New ThreadStart (Ogeturls2.fireURLS);

Thread mythread2 = new thread (Odlegate2); mythread2.start ();

}

To start a thread the ThreadStart () function is called which takes a function pointer (basically a reference that points at a specific method in a class) as an argument. This returns a Delegate that can be used to create a new thread and tell it to start running with this pointer. you can pass either an instance variable of a static address of static class method. In most cases you'll want to use a method of a dynamic instance object variable, because it gives you the ability to fully set up the instance by setting properties that you'll need as part of the processing. Think of the actual thread implementation class as wrapper that is used as the high level calling mechanism and parameter packager to your actual processing code. If you need to pass data back to some other object you can make this instance a member of another object. For example, I could have made this object part of the form which would then allow the form to access the members of the 'thread' class and both could shar e the data.

Creating threads and running them is very easy but make sure you manage your data cleanly to prevent access of shared data from different threads at the same time. Shared data needs to be protected with synchronization of some sort. In fact, you can see why this is an issue if you click the Go link on the sample form a few times while downloads are still running. you'll see the numbers jump back and forth as multiple threads update the same fields on the form. As multiple instances are writing to the labels at the same time the code will eventually blow up. The workaround for this is to use synchronized methods to handle the updates or to use separate forms to display the update information (new form for each request). The topic of synchronization is beyond the Scope of this article and I'll cover Basic Multi-Threading Concepts in a Future Article.The Web At Your Fingertips

This cliché has been so overused, but I can say .NET really delivers on this promise in a number of ways. Yes you could do all of this and most other Internet related things before, but .NET brings a consistent model to the tools. in addition you get straight forward support for advanced features like easy to implement multi-threading and (albeit somewhat complex) event support that make it easy to created complex applications that utilize the tools in ways that were either not possible in, or took a lot More work previously.

The tools are all there to access the Web very easily whether it's through the high level tools in .NET or the more lower level network protocol classes. The HttpWebRequest class is a fairly easy and powerful implementation that provides an excellent balance between flexibility and ease of use. For me the wwHttp class has been an exercise in understanding and utilizing the HttpWebRequest / Response classes. I hope you find the class useful if not as is then as an example of a variety of things that need to be done with HTTP requests frequently . The class is not complete and some features will need expansion in the future, but it's good starting point.As always if you have questions or comments I and all of Code Magazine's editors and writers welcome them at:

Http://www.west-wind.com/wwthreads/default.asp?forum=code magazine

转载请注明原文地址:https://www.9cbs.com/read-130290.html

New Post(0)