Use. NET access to the Internet (1) Paul

Source: Internet
Author: User
Tags abstract date command line ftp header implement interface socket
The Microsoft. NET Framework provides a tiered, scalable, and managed implementation of Internet services that you can quickly and easily integrate into your applications. Your applications can be built on pluggable protocols to automatically take advantage of new Internet protocols, or they can use a managed implementation of the Windows sockets interface to work with networks at the socket level.

Introduction of pluggable Protocols


The Microsoft. NET Framework provides tiered, scalable, and managed Internet service implementations that you can quickly and easily integrate into your applications. The Internet access classes in the System.Net and System.Net.Sockets namespaces can be used to implement web-based and internet-based applications.

Internet applications


Internet applications are broadly divided into two categories: client applications (Request information) and server applications (in response to information requests from clients). A typical Internet client-server application is the World Wide Web, where people use browsers to access documents and other data stored on WEB servers around the world Wide.
Applications are not limited to just one role; for example, the familiar middle-tier application server responds to client requests by requesting data from other servers, in which case it serves both as a server and as a client.
A client application makes a request by identifying the requested Internet resource and the communication protocol used for that request and response. If necessary, the client also provides any additional data required to complete the request, such as proxy location or authentication information (user name, password, and so on). The request can be sent to the server as long as it constitutes a request.

Identify resources


The. NET framework uses a Uniform Resource Identifier (URI) to identify the requested Internet resources and communication protocols. The URI consists of at least three (and possibly four) fragments: The schema identifier (the communication protocol that identifies the request and the response), the server identifier (consisting of a domain Name System (DNS) hostname or a TCP address that uniquely identifies the server on the Internet), Path identifiers (locating the information requested on the server) and an optional query string (transferring information from the client to the server). For example, the URI "Http://www.contoso.com/whatsnew.aspx?date=today" is the scenario identifier "HTTP", the server Identifier "www.contoso.com", the path whatsnew.aspx "and the query string"? Date=today ".
As soon as the server receives the request and responds, it returns the response to the client application. The response includes supplemental information, such as the type of the content (such as raw text or XML data).

Requests and responses in the. NET Framework


The. NET framework uses specific classes to provide the three pieces of information needed to access the Internet through the request/response model: The URI class (which contains the URI of the Internet resource you are looking for), The WebRequest class (which contains the request for that resource), and the WebResponse Class (provides a container for incoming responses).
The client application creates a URL by passing the URI of the network resource to the WebRequest.Create method. WebRequestInstance. This static method creates a specific protocol (for example, HTTP) WebRequestInstance. Returned by WebRequestInstances provide access to properties that both control requests to the server and control access to the data stream that is sent when the request is established. WebRequestThe GetResponse method on the instance sends a request from the client application to the server identified in the URI. In cases where the response may be delayed, you can use the WebRequestThe BeginGetResponse method on the instance asynchronously establishes the request and can use the EndGetResponse method to return the response at a later time.
GetResponseAnd EndGetResponsemethod returns a WebResponseinstance that provides access to the data returned by the server. Because this data is provided by the GetResponseStream method as a stream to the requesting application, it can be used anywhere in the application where the data flow is used.
WebRequestClasses and WebResponseA class is the foundation of a pluggable protocol--an implementation of a network service that allows you to develop applications that use Internet resources without worrying about the specific details of the protocols that each resource uses. Use WebRequestClass Registration WebRequest's descendant classes can manage detailed information about establishing actual connections to Internet resources.
For example, the HttpWebRequest class manages detailed information about using HTTP to connect to Internet resources. By default, when WebRequest.CreateMethod encounters a URI that starts with an "http:" or "https:" (HTTP and secure HTTP protocol identifier), the returned WebRequestAn instance can be used as is, or it can be converted to a type HttpWebRequestTo access protocol-specific properties. In most cases, WebRequestInstance provides all the information necessary to establish a request.
Any protocol that can be represented as a request/response transaction can be WebRequestUsed in. You can from WebRequestAnd WebResponseExport protocol-specific classes, and then register them through the static WebRequest.RegisterPrefix method for use by your application.
When requesting client authentication for an Internet request, WebRequestProvides the necessary credentials for the Credentials property. These credentials can be simple name/password pairs for basic HTTP or Digest authentication, or name/password/domain groups for NTLM or Kerberos authentication. A set of credentials can be stored in the NetworkCredentials instance, or multiple sets of credentials can be stored in the CredentialCache instance at the same time. CredentialCacheUse the URI of the request and the authentication scheme supported by the server to determine which credentials will be sent to the server.

Simple request via WebClient


For applications that need to establish simple requests for Internet resources, the WebClient class provides public methods for uploading data to or downloading data from an Internet server. WebClientDepend on WebRequestclass to provide access to Internet resources; WebClientA class can use any registered pluggable protocol.
For applications that cannot use the request/response model, or for applications that need to listen on the network and send requests, System.Net.SocketsNamespaces provide TcpClient classes, TcpListener classes, and UdpClient classes. These classes handle the details of establishing a connection using different transport protocols and expose the network connection as a flow to the application.
Developers who are familiar with the Windows sockets interface, or who need control by programming at the socket level, will find System.Net.SocketsClasses can meet their needs. The System.Net.Sockets class is a conversion point from managed to native code in the System.Net class. In most cases, the System.Net.Sockets class marshals data to its Windows 32-bit copy and handles any required security checks.

Request data


Developing applications running in today's Internet distributed operating environments requires an efficient, easy-to-use way to retrieve data for all types of resources. Pluggable protocols allow you to develop applications that retrieve data from multiple Internet protocols using a single interface.
For simple request and response transactions, the WebClient class provides the easiest way to upload data to an Internet server or download data from an Internet server. WebClientProvides methods for uploading and downloading files, sending and receiving streams, and sending data buffers to the server and receiving responses. WebClientUse the WebRequest class and the WebResponse class to establish a physical connection to an Internet resource so that all of the pluggable protocols that you register are available for use. The following example requests a Web page and returns the result in the stream.
[C #]
WebClient myclient = new WebClient ();
Stream response = Myclient.openread ("http://www.contoso.com/index.htm");
The stream data is used here.
Response. Close ();

Client applications that require more complex transactions use the WebRequestClass and its descendants to request data from the server. WebRequestEncapsulates details that connect to the server, send requests, and receive responses. WebRequestis an abstract class that defines a set of properties and methods that can be used for all applications that use pluggable protocols. WebRequest's descendants (for example, HttpWebRequest) are implemented by the WebRequestDefines the properties and methods that are adopted in a manner consistent with the underlying protocol.
WebRequestClass to determine the specific instance of a derived class to create by using the value of the URI passed to its Create method, creating WebRequestA protocol-specific instance of the descendant. The application registers a descendant's constructor by using the WebRequest.RegisterPrefix method, indicating which WebRequestThe descendant should be used to process the request.
by calling WebRequestThe GetResponse method on the instance to establish a request for Internet resources. GetResponseMethod constructs are derived from the WebRequestinstance, establish a TCP or UDP socket connection to the server, and send the request. For requests to send data to the server, such as HTTP Postor FTP putRequest, the Webrequest.getrequeststream method provides the network stream to which data is sent.
GetResponsemethod returns the WebRequestMatching protocol-specific WebResponse, as shown in the following example.
[C #]
WebRequest req = webrequest.create ("http://www.contoso.com/");
WebResponse resp = req. GetResponse ();

WebResponseClass is also an abstract class that defines the properties and methods of all applications that can be used to use pluggable protocols. WebResponseThe descendants implement these properties and methods for the underlying protocol. For example, the HttpWebResponse class implementation is used for HTTP WebResponseClass.
The data returned by the server is provided to the application in the stream returned by WebResponse.GetResponseStream. You can use this stream just as you would with any other stream, as shown in the following example.
[C #]
StreamReader sr =
New StreamReader (resp. GetResponseStream (), encoding.ascii);

Create an Internet request


The application creates the WebRequest instance through the WebRequest.Create method. This is the creation of descendants WebRequestThe static method of the instance, based on the URI scheme passed to the instance.
The. NET Framework provides inheritance from WebRequestHttpWebRequest class to handle HTTP and HTTPS requests for the Internet. In most cases, WebRequestProvides all the attributes you need to create a request, but if necessary, you can WebRequest.Createmethod is created by the WebRequestThe object type is converted to HttpWebRequestTo access the HTTP-specific properties of the request.
HttpWebResponseHandles the response to HTTP and HTTPS requests for the Internet. To access HttpWebResponseHTTP-specific properties, you need to set the WebResponseType is converted to HttpWebResponse.
To handle requests that use other Internet protocols, such as FTP, you need to export WebRequestAnd WebResponseProtocol-specific descendants of the.

Using the Internet request and response classes


to request data from the Internet and read the response, use the following procedure.
If you want to access resources such as Web pages, create a WebRequest instance by calling WebRequest.Create with the URI of the resource you want to use, as shown in the following example.
[C #]
WebRequest wreq = WebRequest.Create ("http://www.contoso.com/");
AttentionThe. NET Framework provides protocol-specific for URIs that begin with "http:", "https:", and "File:" WebRequestAnd WebResponseOffspring. To access other protocols, you must implement a protocol-specific WebRequestAnd WebResponseOffspring.
In WebRequestTo set any required property values in an instance. For example, to support authentication, set the Credentials property to an instance of the NetworkCredential class, as shown in the following example.
[C #]
Wreq.credentials =
New NetworkCredential ("username", "password");
In most cases, WebRequestThe instance itself is sufficient to send and receive data. However, if you need to set protocol-specific properties, you will WebRequestinstance into a protocol-specific instance. Only when processing WebRequestOf WebRequestThis type of conversion is valid when the descendant is correct. For example, to access the HTTP-specific properties of HttpWebRequest, you would WebRequestConverted to HttpWebRequest。 The following code example shows how to set the HTTP-specific useragent property.
[C #]
if (Wreq is HttpWebRequest)
{
((HttpWebRequest) wreq). useragent = ". NET Framework Example Client";
}
To download resources from the Internet, call the WebRequestMethod of GetResponse.
To send or upload data to a resource, call the WebRequestGetRequestStream method and writes the data using the result Stream object. After the upload is complete, the request flow must be closed using the Stream.Close method. After you close the stream, you can call GetResponseTo ensure that the server has received the data correctly. The actual class returned for the WebResponse instance is determined by the requested URI scheme. The following code example shows how to use the GetResponseMethod creates WebResponseInstance.
[C #]
WebResponse wresp = Wreq.getresponse ();
AttentionCall WebResponseAfter you must use the WebResponse.Close or Stream.CloseCloses the response. If you do not close each response, the application will run out of connections to the server and cannot process other requests.
Use WebResponseThe GetResponseStream method of the instance gets the stream containing the response data from the network resource. You can also access WebResponseInstance or the property of the WebResponseinstance into a protocol-specific instance to read protocol-specific properties. For example, to access the HTTP-specific properties of HttpWebResponse, you would WebResponseConverted to HttpWebResponse。 The following code example shows how to access HTTP-specific properties and read response streams.
[C #]
Read a http-specific property.
if (Wresp is HttpWebResponse)
{
DateTime Updated = ((HttpWebResponse) wresp). LastModified;
}
Get the response stream.
Stream Respstream = Wresp.getresponsestream ();

This is example uses a StreamReader to read the entire response
into a string and then writes the string to the console.
StreamReader reader = new StreamReader (Respstream, ENCODING.ASCII);
String resphtml = reader. ReadToEnd ();
Console.WriteLine (resphtml);

Close the response stream.
Respstream.close ();
If the application only needs WebResponseand ignores any returned data, you do not have to get the response stream. The following code example shows how to return server header information from an Internet host.
[C #]
WebRequest wreq = WebRequest.Create ("http://www.contoso.com");
WebResponse wresp = Wreq.getresponse ();
String server = wresp.headers["Server"];
After reading the data in the response, you must use the Stream.CloseMethod closes all open streams or uses the WebResponse.CloseMethod closes the response.
[C #]
Wresp.close ();
Does not have to be in response stream and WebResponseis called on the instance Closemethod, but there is no harm in doing so. WebResponse.CloseCalled when a response is closed Stream.Close
The following sample application description WebRequestAnd WebResponseThe use of the class.
[C #]
Using System;
Using System.Net;
Using System.Text;
Using System.IO;

Class Clientget {
public static void Main (string[] args)
{
if (args. Length < 1)
{
Showusage ();
Return
}

Get the URI from the command line.
URI site = new Uri (Args[0]);
Create the request instance.
WebRequest wreq = webrequest.create (site);
Set the Http-specific useragent property
if (Wreq is HttpWebRequest)
{
((HttpWebRequest) wreq). UserAgent =
". NET Framework Example Client";
}
Get the response instance
WebResponse wresp = Wreq.getresponse ();
Read a http-specific property.
if (Wresp is HttpWebResponse)
{
DateTime updated = ((HttpWebResponse) wresp). LastModified;
}
Get the response stream.
Stream Respstream = Wresp.getresponsestream ();
This is example uses a StreamReader to read the entire response
into a string and then writes the string to the console.
StreamReader reader =
New StreamReader (Respstream, ENCODING.ASCII);
String resphtml = reader. ReadToEnd ();
Console.WriteLine (resphtml);
Close the response and response stream.
Wresp.close ();
}
public static void Showusage ()
{
Console.WriteLine ("Attempts to get a URI.");
Console.WriteLine ("\r\nusage:");
Console.WriteLine ("Clientget URI");
Console.WriteLine ("Example:");
Console.WriteLine ("Clientget http://www.contoso.com/");
}
}

Using streams on the network


network resources are represented as streams in the. NET framework. The. NET Framework provides the following features for general processing through convection:
    • A common way to send and receive WEB data. The application uses Stream.Write and Stream.read to send and receive data, regardless of the actual content of the file (HTML, XML, or anything else).
    • The entire framework of mid-stream compatibility. Flow is used throughout the. NET framework, which has a rich structure for handling streams. For example, by modifying just a few lines of code for the initialization stream, you can modify the application that reads the XML data from FileStream to read the data from the NetworkStream instead. The main difference between a NetworkStream class and another stream is that theNetworkStream is not found, and the CanSeek property always returns false, and the Seek and Position method to raise NotSupportedException.
    • Processes data when data arrives. Instead of forcing applications to wait for the entire dataset to download, the stream provides access to the data as it downloads from the Internet.

The System.Net.Sockets namespace contains a NetworkStreamClass that implements a Stream class that is dedicated to the Internet. Class in the System.Net.Sockets namespace uses the NetworkStreamclass represents a stream.
To send data using the returned flow to the network, call GetRequestStream on the WebRequest instance. WebRequestSend the request header to the server, and you can then send the data to the Internet resource by invoking the BeginWrite, EndWrite, or Write method on the returned stream. Some protocols, such as HTTP, may require protocol-specific properties to be set before data is sent. The following code example shows how to set HTTP-specific properties for sending data. The example assumes that the variable SendData contains the data to send, and the variable sendlength is the number of bytes of data to send.
[C #]
HttpWebRequest request =
(HttpWebRequest) WebRequest.Create ("http://www.contoso.com/");
Request. method = "POST";
Request. ContentLength = Sendlength;
Try
{
Stream Sendstream = Request. GetRequestStream ();
Sendstream.write (senddata,0,sendlength);
Sendstream.close ();
}
Catch
{
Handle errors ...
}
To receive data from the network, call GetResponseStream on the WebResponse instance. You can then read data from Internet resources by invoking the BeginRead, EndRead, or Read method on the returned stream.
Keep the following points in mind when using streams from network resources.
    • The CanSeek property always returns falsebecause the NetworkStream class cannot change the position in the stream. the Seek and Position methods raise the NotSupportedException.
    • When using WebRequest and WebResponse , the stream instance created by calling GetResponseStream is read-only, by calling the the stream instance created by GetRequestStream is write-only.
    • Using the StreamReader class makes coding easier. The following code instance uses StreamReader to read an ASCII-encoded stream from the WebResponse instance (this example does not show how to create a request).
    • If network resources are not available, calls to GetResponse may block. You should consider using the BeginGetResponse and EndGetResponse methods to use asynchronous requests.
    • When you create a connection to a server, calls to GetRequestStream may block. Consideration should be given to using the BeginGetRequestStream and EndGetRequestStream methods for streaming asynchronous requests.

[C #]
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 your are through with the stream to close
S




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.