The Microsoft .NET framework provides hierarchical, scalable and managed implementations of Internet services, you can quickly integrate these Internet services to your application. Your app can be based on the plug-in protocol to automatically utilize new Internet protocols, or they can use the hosted hosted intersection of the Windows socket interface to use the network on the socket level.
Introducing plug-in protocol
The Microsoft .NET framework provides hierarchical, scalable and hosted Internet service implementations, you can quickly and easily integrate them into your application. The Internet Access class in System.Net and System.Net.Sockets Namespaces can be used to implement web and Internet-based applications.
Internet application
The Internet application is generally divided into two categories: client applications (request information) and server applications (responding to information requests from the client). A typical Internet client-server application is World Wide Web, in the World Wide Web, people use browsers to access documents and other data stored on Web servers around the world.
The application is not limited to only one of the characters; for example, the intermediate application server familiar to everyone responds to the client's request by requiring the data of other servers, in which case the server, as a client, as a client .
The client application issues a request by identifying the requested Internet resources and a communication protocol for the request and a response. If necessary, the client also provides any additional data required to complete the request, such as proxy location or authentication information (username, password, etc.). This request can be sent to the server as long as the request is constituted.
Logo resources
The .NET Framework uses a Unified Resource Identifier (URI) to identify the requested Internet resources and communication protocols. The URI is at least three (or may be four) fragments: the scheme identifier (identifies the communication protocol for request and response), the server identifier (by the Domain Name System (DNS) host name or TCP address for unique Identify the server on the Internet), path identifier (information requested on the server) and optional query strings (send information from the client to the server). For example, the URI "http://www.contoso.com/whatsnew.aspx?date=today" is by the scheme identifier "http", server identifier "www.contoso.com", path "whatsnew.aspx" and query String "? Date = Today" consists of.
As long as the server receives the request and responds, it returns the response to the client application. The response includes supplementary information, such as the type of content (eg, original text or XML data).
Requests and responses in the .NET framework
The .NET framework uses a specific class to provide three parts required by requesting / responding to accessing the Internet: URI class (including URI of the Internet resource you want to find), WebRequest class (including request to this resource) and WebResponse class Provide containers for incoming response).
The client application creates a WebRequest instance by passing the URI of the network resource to the WebRequest.create method. This static method creates a WebRequest instance for specific protocols (such as http). The returned WebRequest instance provides access to the attribute, which controls both the request for the server and controls the traffic transmitted when the request is established. The GetResponse method on the WebRequest instance sends a request from the client application to the server identified in the URI. In the case where the response may be delayed, you can use the BegingeTResponse method on the WebRequest instance asynchronously established requests, and you can use the EndgetResponse method to return response later. GetResponse and EndgetResponse methods returns a WebResponse instance that provides access to the data returned to the server. Because this data is provided by the getResponseStream method, it provides an application to the application, so it can use anywhere in the application in the application.
The WebRequest class and the WebResponse class are the foundation of the plug-in protocol - this is an implementation of a network service that allows you to develop the specific details of the protocol used by each resource when developing applications using Internet resources. information. Sub-generation with WebRequest class WebRequest can manage detailed information about establishing actual connections to the Internet resource.
For example, HTTPWebRequest class management is more information about using HTTP to connect to the Internet resource. By default, when the WebRequest.create method encounters the URI starting with "http:" or "https:" (HTTP: "or" Protocol Identifier), the returned WebRequest instance can be used as it is, or can be converted For HTTPWebRequest to access protocol-specific properties. In most cases, WebRequest instances provide all the information necessary to establish requests.
All protocols that can be represented as request / response transactions can be used in WebRequest. You can export protocol-specific classes from WebRequest and WebResponse, and then register them through static WebRequest.registerPrefix methods to use it for use.
When the client authentication requesting the Internet request, the WebRequest's Credentials property provides the required credentials. These credentials can be a simple name / password pair for basic HTTP or brief authentication, or a name / password / domain group 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. CredentialCache uses the requested URI 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 require simple requests for Internet resources, the WebClient class provides public methods that upload data to the Internet server or download data from the Internet server. WebClient relies on the WebRequest class to provide access to the Internet resource; therefore, the WebClient class can use any registered plug-in protocol.
For applications that cannot use request / response models, or for applications that need to listen to the network and send requests, System.Net.Sockets namespace provides TCPClient classes, TCPListener classes, and UDPCLIENT classes. These class processing uses different transmission protocols to establish the details of the connection and disclose the network connection as the flow to the application. For developers who are familiar with Windows sockets or developers who need to be programs provided by the socket level, they will find that the System.Net.Sockets class can meet their needs. The System.Net.Sockets class is a conversion point from the host code in the hosted to the System.NET class. In most cases, the System.Net.Sockets class seals the data to its Windows 32-bit replica, and handles any necessary security checks.
Request data
Developed applications running in today's Internet Distributed operating environment requires efficient and easy-to-use methods to retrieve all types of resources data. Plugable protocols allow you to develop applications that use a single interface to retrieve data from multiple Internet protocols.
For simple requests and response transactions, the WebClient class provides the easiest way to upload data to the Internet server or download data from the Internet server. WebClient provides methods for uploading and downloading files, sending and receiving streams, and sending data buffers to servers and receiving responses. WebClient uses the WebRequest class and the WebResponse class to establish actual connections to the Internet resource to register all plug-in protocols available. The following example requests the 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 buy here.
Response.close ();
A client application that needs more complex transaction processing uses the WebRequest class and its child to request data in the server. WebRequest packages are connected to the server, send requests and receive details of the response. WebRequest is an abstract class that defines a set of properties and methods available to all applications that use the plug-in protocol. WebRequest's child (such as httpwebrequest) implements the properties and methods defined by WebRequest, which is consistent with the basic protocol.
The WebRequest class determines the specific derivative instance to be created by using the value of the URI passed to its CREATE method, and create a specific instance of the WebRequest sub-generation. The application indicates which WebRequest child response is used to process the request by using the constructor of the sub-generation.
Create a request for Internet resources by calling the getResponse method on the WebRequest instance. The GetResponse method constructs a protocol-specific request from the attribute of the WebRequest instance, establishes the TCP or UDP socket connection connection with the server and sends the request. For requests to send data to the server, such as HTTP POST or FTP PUT requests, the WebRequest.getRequestStream method provides the network stream to be sent therein.
GetResponse method Returns a specific WebResponse, which matches WebRequest, as shown in the following example.
[C #]
WebRequest Req = WebRequest.create ("http://www.contoso.com/);
WebResponse Resp = Req.getResponse (); WebResponse class is also an abstract class that defines properties and methods for all applications that can be used to use plug-in protocols. WebResponse children implements these properties and methods for basic protocols. For example, the HTTPWebResponse class implements the WebResponse class for HTTP.
The data returned by the server is provided to the application in the stream returned by WebResponse.getResponseSstream. You can use this stream like 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 a WebRequest instance via the WebRequest.create method. This is a static method of creating a subtribution WebRequest instance (based on the URI scheme passed to the instance).
The .NET framework provides an HTTPWebRequest class that inherits from WebRequest to handle HTTP and HTTPS requests for Internet. In most cases, WebRequest provides all the properties you need to build requests; however, if necessary, you can convert WebRequest object types created through WebRequest.create methods to HttpWebRequest to access the requested HTTP-specific properties.
HttpWebResponse handles the response to HTTP and HTTPS requests for Internet. To access the HTTP specific properties of HTTPWebResponse, you need to convert the WebResponse type to HttpWebResponse.
To process requests using other Internet protocols (eg, FTP), you need to export WebRequest and WebResponse protocol specific sub-generations.
Use Internet requests and response classes
To request data from the Internet and read response, use the following steps.
If you want to access resources like a web page, create a WebRequest instance by calling WebRequest.create with the URI to use, as shown in the following example.
[C #]
WebRequest WREQ = WebRequest.create ("http://www.contoso.com/);
Note that the .NET framework provides protocol-specific WebRequest and WebResponse subscribers with "http:", "https:" and "File:". To access other protocols, you must implement protocol-specific WebRequest and WebResponse children.
Set any desired properties in the WebRequest instance. For example, if you want 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, the WebRequest instance itself is sufficient to send and receive data. However, if you need to set a specific properties of the protocol, the WebRequest instance is converted to a specific instance of the protocol. This type conversion is only valid when the WebRequest's WebRequest child is processed. For example, if you want to access the HTTP-specific properties of HTTPWebRequest, convert WebRequest to HttpWebRequest. The following code instance shows how to set the HTTP-specific useERAGENT property. [C #]
IF (Wreq Is HttpwebRequest)
{
(Httpwebrequest) .Userage = ".NET Framework Example Client";
}
To download resources from an Internet, call WebRequest's getResponse method.
To send data or upload data, call WebRequest's getRequestStream method and write data using the result stream object. Once upload, you must use the stream.close method to close the request stream. After closing the flow, you can call GetResponse to make sure the server has received data correctly. Decide on the actual Class of the WebResponse instance to be requested. The following code instance shows how to create a WebResponse instance using the getResponse method.
[C #]
WebResponse WRESP = WREQ.GETRESPONSE ();
Note When you call WebResponse, you must use WebResponse.close or Stream.Close to close the response. If each response is not closed, the application will use the connection with the server without processing other requests.
GetResponseStream methods using the WebResponse instance gets streams that contain the response data from the network resource. You can also access the properties of the WebResponse instance or convert the WebResponse instance to a protocol-specific instance to read the specific properties of the protocol. For example, to access the HTTPWebResponse's HTTP-specific properties, convert WebResponse to HttpWebResponse. The following code example shows how to access HTTP-specific properties and read responses.
[C #]
// read an http-specific property.
IF (WRESP IS HTTPWEBRESPONSE)
{
DateTime Updated = (httpwebresponse) WRESP) .lastmodified;
}
// Get The Response Stream.
Stream Respstream = WRESP.GETRESPONSESTREAM ();
// this Example Uses a streamreader to read the entire response
// into a string and when 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 the header information returned in WebResponse and 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.close method to close all open streams or use the WebResponse.close method to shut down the response.
[C #]
WRESP.CLOSE ();
There is no need to call the Close method on the response stream and the WebResponse instance, but there is no harm to do this. WebResponse.close calls stream.close when the response is turned off.
The following sample application describes the usage of WebRequest and WebResponse classes.
[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 Requestance.
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 an http-specific property.
IF (WRESP IS HTTPWEBRESPONSE)
{
DateTime Updated = (httpwebresponse) WRESP) .lastmodified;
}
// Get The Response Stream.
Stream Respstream = WRESP.GETRESPONSESTREAM ();
// this Example Uses a streamreader to read the entire response
// into a string and when 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 Street.
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/);
}
}
Use flow on the network
Network resources are expressed in the .NET framework. The general processing is performed by convection, the .NET framework provides the following features:
A general method of sending and receiving web data. Regardless of the actual content of the file (HTML, XML, or anything else), the application will send and receive data using stream.write and stream.read.
Compatibility of the entire framework. For the entire .NET framework, this framework has a rich structure to process flow. For example, by modifying a few lines of code of the initialization stream, you can modify an application that reads XML data from the FILESTREAM to make it read from NetWorkStream. The main difference between the NetWorkStream class and other streams is that NetWorkStream is unconcerned, and the canseek property always returns false, while the Seek and Position methods trigger NotSupportedException.
Processing data when data arrives. The stream provides access to the data from the Internet Download, not the mandatory application waits for downloading the full data set.
System.net.sockets Namespace contains a NetWorkStream class that implements a Stream class that is specifically used for Internet. The class in the System.Net.Sockets namespace uses the NetworkStream class to represent streams.
To send data to the network to the network, call GetRequestStream on the WebRequest instance. WebRequest sends the data to the Internet resource by calling the BEGINWRITE, ENDWRITE or WRITE method by calling the BEGINWRITE, ENDWRITE or WRITE method on the returned stream. Some protocols (such as http) may require setting protocol specific properties before sending data. The following code example shows how to set the HTTP-specific properties for the sending data. This example assumes that the variable SendData contains the data to be transmitted, and the variable SendLength is the number of data bytes to be transmitted.
[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 GetResponseSteream on the WebResponse instance. You can then call the BEGINREAD, EndRead or Read method on the return stream, read data from the Internet resource.
Remember the following points when using the flow from the network resource.
Since the NetWorkStream class cannot change the position in the stream, the Canseek property always returns false. Seek and Position methods trigger NotSupportedException. When using WebRequest and WebResponse, the stream instance created by calling GetResponseStream is read-only, and the stream instance created by calling getRequestStream is only written.
Use the StreamReader class to make the encoding easier. The following code instance uses streamReader from the WebResponse instance stream with ASCII encoding (this example does not display how to create a request).
If the network resource is not available, the call to getResponse may be blocked. It should be considered to use the BegingeTResponse and EndgetResponse methods to use asynchronous requests.
When you create a connection to the server, the call to getRequestStream may blocked. The asynchronous request should be considered using the BegingerEtRequestStream and EndgetRequestStream methods.
[C #]
// CREATE A Response Object.
WebResponse response = Request.getResponse ();
// Get a ready stream from the server.
StreamReader SR =
New streamreader (response.getResponsestream (), encoding.ascii;
// Use the stream. Remember when you are through with the stream to close
sr.close ();