Use. Net to access the Internet (2)

Source: Internet
Author: User
Implement Asynchronous requests for the system. Net class to use the standard asynchronous programming model of the. NET Framework for asynchronous access to Internet resources. The begingetresponse and endgetresponse methods of the webrequest class start and complete asynchronous requests to Internet resources respectively.
Note: Using synchronous calls in asynchronous callback methods may cause serious performance degradation. Pass Webrequest For Internet requests implemented by and its children, stream. beginread must be used to read the streams returned by the webresponse. getresponsestream method.
The following C # example Program Describes how to pass Webrequest Class. In this example, a console program obtains a URI from the command line, requests Resources in the URI, and prints data on the console when receiving data from the Internet.
This program defines two classes for your own use: one is Requeststate Class, which transmits data between asynchronous calls; the other is Clientgetasync Class, which implements asynchronous requests to Internet resources.
Requeststate Class retains the Request status between Asynchronous Method calls that serve the request. In Requeststate Class that contains the current resource request and received response streams Webrequest And stream instances, the buffer that contains the data received from Internet resources, and the stringbuilder instance that contains the entire response. When the asynccallback method is Webrequest. begingetresponse At registration, Requeststate Instance (AR) State Parameter transfer.
Clientgetasync Class to Implement Asynchronous requests to Internet resources, and write the result response to the console. This class contains the methods and attributes described in the following list.
The alldone attribute contains an instance of the manualresetevent class. The instance sends a signal indicating that the request has been completed. The main () method reads the command line and starts a request for a specified Internet resource. Create this method Webrequest Instance wreq and Requeststate Instance AR, call Begingetresponse Start processing the request, and then call the alldone. waitone () method so that the application exits after the callback is complete. After reading the response from Internet resources, main () writes the response to the console, and the application ends. The showusage () method writes the sample command line to the console. If the URI is not provided in the command line, main () calls this method. The respcallback () method implements asynchronous callback for Internet requests. This method creates Webresponse Instance to obtain the response stream, and then start to asynchronously read data from the stream. The readcallback () method implements the asynchronous callback Method for reading the response stream. It transfers data received from Internet resources Requeststate Instance Responsedata Attribute, and then start another asynchronous read for the response stream until no data is returned. After reading all the data, readcallback () closes the response stream and calls the alldone. Set () method to indicate Responsedata The response in is complete. Note: Closing all network streams is critical. If all requests and response streams are not closed, the application will use up the server connection and cannot process other requests.

[C #]
Using system;
Using system. net;
Using system. Threading;
Using system. text;
Using system. IO;

// The requeststate class passes data into SS async CILS.
public class requeststate
{< br> const int buffersize = 1024;
Public stringbuilder requestdata;
Public byte [] bufferread;
Public webrequest request;
Public stream responsestream;
// create decoder for appropriate enconding type.
Public decoder streamdecode = encoding. utf8.getdecoder ();
Public requeststate ()
{< br> bufferread = new byte [buffersize];
requestdata = new stringbuilder (string. empty);
request = NULL;
responsestream = NULL;
}< BR >}

// Clientgetasync issues The async request.
Class clientgetasync
{
Public static manualresetevent alldone = new manualresetevent (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 manualresetevent 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 requeststate object from the async result.
Requeststate rs = (requeststate) Ar. asyncstate;

// Get the webrequest from requeststate.
Webrequest Req = Rs. request;

// Call endgetresponse, which produces 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 requeststate object from asyncresult.
Requeststate rs = (requeststate) asyncresult. asyncstate;

// Retrieve the responsestream that was set in respcallback.
Stream responsestream = Rs. responsestream;

// Read Rs. bufferread 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 then 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
// 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 stream.
Responsestream. Close ();
// Set the manualresetevent so the main thread can exit.
Alldone. Set ();
}
Return;
}
}
Use the application protocol. NET Framework to support common application protocols on the Internet. This section describes how to use HTTP in the. NET Framework. , TCP And UDP Supported information and information about using the Windows Socket interface Implement custom protocol information.
The HTTP. NET Framework uses the httpwebrequest and httpwebresponse classes to provide comprehensive support for the HTTP protocol, while the HTTP protocol constitutes a majority of Internet traffic. When the static method webrequest. Create encounters a URI starting with "HTTP" or "HTTPS", these classes derived from webrequest and webresponse are returned by default. In most cases, Webrequest And Webresponse Class provides everything required to generate a request, but if you need to access HTTP-specific features exposed as properties, you can convert these classesHttpwebrequest Or Httpwebresponse .
Httpwebrequest And Httpwebresponse Encapsulate "standard HTTP request and Response" transactions and provide access to common HTTP headers. These classes also support most HTTP 1.1 features, including pipelines, blocks, authentication, pre-authentication, encryption, Proxy Support, server certificate authentication, and connection management. Custom headers and headers that are not provided through properties can be stored in Headers And can be accessed through this attribute.
The following example shows how to access specific HTTP properties. In this example Keep-alive Behavior and obtain 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 returned by the server.
string ver = httpwresp. protocolversion. tostring ();
httpwresp. close ();
httpwebrequest Yes webrequest default class used, you can pass the URI to webrequest. create method.
you can set allowautoredirect attribute to true (default) enables the application to automatically follow HTTP redirection. The application redirects the request, and the responseuri attribute of httpwebresponse contains the actual web resources that respond to the request. If you set allowautoredirect to false , the application must be able to handle HTTP errors.
the application captures the webexception set to webexceptionstatus. protocolerror to receive HTTP protocol errors. The response attribute contains the webresponse sent by the server and indicates the actual HTTP Error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.