Use .NET to access Internet (2)

zhaozj2021-02-17  47

Implement asynchronous request

The system.net class uses the standard asynchronous programming model for the .NET framework to communicate asynchronously. The WebRequest class's BegingeTResponse and EndgetResponse methods are started and completed asynchronous requests for the Internet resource, respectively.

Note that using synchronous calls in asynchronous callbacks may result in severe performance reduction. The Internet request implemented through WebRequest and its sub-generation must be read using stream.beneread to read the stream returned by the WebResponse.getResponseSstream method.

The following C # sample program explains how to use asynchronous calls through the WebRequest class. This example is a console program that obtains the URI from the command line, requested the resources at this URI, and then print data on the console during the console from the Internet from the Internet.

The program defines two classes for yourself: one is the RequestState class, which delivers data between asynchronous calls; the other is the ClientGetasync class, which implements asynchronous requests for Internet resources.

The REQUESTSTATE class reserves the state of the request in the asynchronous method call service to the request. In the RequestState class, there is a WebRequest and Stream instance containing the current resource request and the received response stream, which contains a buffer that is currently received from the Internet resource, and a StringBuilder instance containing the entire response. When the AsyncCallback method is registered with WebRequest.BegingeTResponse, the RequestState instance (AR) is passed as a State parameter.

The ClientGetasync class implements asynchronous requests for Internet resources and writes the results to the console. This class contains the methods and properties described in the following list.

The alldone property contains an instance of the ManualResetEvent class that issues a signal indicating that the request has been completed.

The main () method reads the command line and starts a request to specify the Internet resource. This method creates WebRequest instance WREQ and REQUESTSTATE AR, calling BeGingeTResponse to start processing request, then call the alldone.waitone () method to make the application exit after the callback is completed. After reading the response from the Internet resource, Main () is written to the console in response, and then the application ends.

SHOWUSAGE () method Write the sample command line to the console. This method will be called if the URI is not provided in the command line.

The RespCallback () method is an asynchronous callback method for the Internet request. This method creates a WebResponse instance containing a response from an Internet resource to get the response stream, and then begin asynchronously reading data from the stream.

The readcallback () method implements an asynchronous callback method for reading response streams. It transmits the data received from the Internet resource to the responseData property of the RequestState instance, and then start another asynchronous reading to the response stream until the data returns until the data is returned. After reading all the data, ReadCallback () turns off the response stream, and calls the alldone.set () method to indicate the response in ResponseData is complete.

Be careful to close all network flows. If all requests and responses are not turned off, the application will run the server connection without processing other requests.

[C #]

Using system;

Using system.net;

Using system.threading;

Using system.text;

Using system.io;

// The Requestte Class Passs Data Across Async Calls.public Class RequestState

{

Const int buffersize = 1024;

Public StringBuilder RequestData;

PUBLIC BYTE [] BufferRead;

Public WebRequest Request;

Public stream responsestream;

// CREATE DECODER for Approrate Enconding Type.

Public decoder streamdecode = encoding.utf8.getdecoder ();

Public requestState ()

{

Bufferread = new byte [buffersize];

RequestData = New StringBuilder (String.empty);

Request = NULL;

Responsestream = NULL;

}

}

// ClientGetasync Issues the async request.

Class ClientGetasync

{

Public Static ManualReveTevent Alldone = New ManualReveTevent (false);

Const int buffer_size = 1024;

Public static void main (string [] args)

{

IF (args.length <1)

{

SHOWUSAGE ();

Return;

}

// Get The Uri from The Command Line.

URI httpsite = new uri (args [0]);

// CREATE The Request Object.

WebRequest WREQ = WebRequest.create (httpsite);

// CREATE The State Object.

RequestState RS = New RequestState ();

// Put The Request Into The State Object So It Can Be Passed Around.

rs.Request = WREQ;

// Issue the async request.

IASYNCRESULT R = (IASYNCRESULT) WREQ.BEGINGETRESPONSE

New AsyncCallback (RespCallback), RS);

// Wait Until The ManualReveTevent Is Set So That The Application

// DOES NOT EXIT UNTIL AFTER THE CALLBACK IS CALLED.

Alldone.waitone ();

Console.writeline (RS.RequestData.toString ());

}

Public static void showusage () {

Console.writeline ("Attempts to Get A URL);

Console.writeline ("/ r / nusage:");

Console.writeline ("ClientGetasync URL);

Console.writeline ("EXAMPLE:");

Console.writeline ("ClientGetasync http://www.contoso.com/);

}

Private Static Void RespCallback (IASYNCRESULT AR)

{

// Get The Requestte Object from the async result.

RequestState RS = (RequestState) ar.asyncState;

// Get The WebRequest from RequestState.

WebRequest Req = rs.Request;

// Call EndgetResponse, Which Products The WebResponse Object

// That Came from the Request Issued Above.

WebResponse Resp = Req.EndgetResponse (AR);

// Start Reading Data from The Response stream.

Stream responsestream = Resp.getResponsestream ();

// store the response stream in requestState to read

// The stream asynchronously.

Rs.ResponseStream = responsestream;

// Pass rs.bufferread to beginread. Read data INTO RS.BUFFERREAD

IASYNCRESULT IARREAD = ResponseStream.beginread (Rs.BufferRead, 0,

Buffer_size, New AsyncCallback (ReadCallback), RS);

}

Private Static Void ReadCallback (IasyncResult AsyncResult)

{

// Get The Requestte Object from AsyncResult.

RequestState RS = (RequestState) asyncResult.asyncState;

// Retrieve The ResponseStream That Was Set in RespCallback.

Stream responsestream = rs.Responsestream;

// read rfferread to verify That It Contains Data.

INT read = responsestream.endread (asyncResult);

IF (read> 0)

{

// prepare a char Array Buffer for Converting to Unicode.

Char [] charbuffer = new char [buffer_size];

// Convert byte stream to char Array and the to string.

// Len Contains The Number of Characters Converted to Unicode.

INT LEN =

Rs.StreamDecode.getChars (Rs.Bufferread, 0, Buffer_SIZE, Charbuffer, 0);

String str = new string (Charbuffer, 0, LEN);

// Append the Recently Read Data to the RequestData StringBuilder

// Object Contained in RequestState.

rs.RequestData.Append (

Encoding.ascii.getstring (Rs.Bufferread, 0, Read); // Continue Reading Data Until

// ResponseStream.endread Returns -1.

IASYNCRESULT AR = ResponseStream.beginread (

Rs.bufferread, 0, buffer_size,

New asyncCallback (READCALLBACK), RS);

}

Else

{

IF (rs.RequestData.length> 0)

{

// Display data to the console.

String strcontent;

StrContent = rs.RequestData.toString ();

}

// Close Down The Response Street.

ResponseSstream.Close ();

// set the manualReveTevent so the main thread can exit.

alldone.set ();

}

Return;

}

}

Using Application Protocol

The .NET Framework supports the Internet's application protocol on the Internet. This section includes information about the use of HTTP, TCP, and UDP support in the .NET framework, and information on custom protocols on using the Windows socket interface.

HTTP

The .NET framework uses the HTTPWebRequest and HttpWebResponse classes to provide full support to the HTTP protocol, and the HTTP protocol constitutes most Internet traffic. Whenever the static method WebRequest.create encounters the URI starting with "HTTP" or "HTTPS", these classes derived from WebRequest and WebResponse will be returned by default. In most cases, WebRequest and WebResponse classes provide everything you need to generate requests, but if you need to access the HTTP specific feature that is disclosed as an attribute, you can convert these classes to HttpWebRequest or httpwebresponse.

HTTPWebRequest and HTTPWebResponse package "Standard HTTP Requests and Response" transactions and provide access to Universal HTTP headers. These classes support most HTTP 1.1 features, including pipelines, block areas, authentication, pre-authentication, encryption, proxy support, server certification, and connection management. Custom headers and headers not provided by attributes can be stored in the headers property and access it through this property.

The following example shows how to access the HTTP-specific properties, in this example, close the HTTP Keep-Alive behavior and get the protocol version number from the web server.

[C #]

HttpWebRequest httpwreq =

(Httpwebrequest) WebRequest.create ("http://www.contoso.com");

// Turn Off Connection Keep-Alives.

HttpWReq.keepalive = false;

HttpWebResponse httpwresp = (httpwebresponse) httpwreq.getResponse ();

// Get the http protocol version number return by the server.

String Ver = httpwresp.protocolversion.tostring ();

Httpwresp.close ();

HttpWebRequest is the default class used by WebRequest, and you can pass the URI to the WebRequest.create method without registering it. You can automatically follow the HTTP redirection by setting the AlLowAutoredIRect property to true (default). The application will redirect requests, and HTTPWebResponse's Responseuri property will contain actual Web resources for the response request. If you set the allowAutoredirect to false, the application must be able to handle redirection as an HTTP protocol.

The application is set to WebExceptionStatus.ProtocoleRror's WebException by capturing status to receive HTTP protocol errors. The Response property contains WebResponse sent by the server and indicates the actual HTTP error.

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

New Post(0)