关于WebRequest类、WebResponse类 WebClient类 的彻底介绍

编者按:通过以下的介绍和样例,我们可以看到:1WebRequest类、WebResponse类是请求响应模型,任务是从URL拉回数据。2WebClient类不但可以拉回数据,还可以向URL推回数据。3、从继承关系上来讲,两组类无任何关系。4、前一组类工作在高的层次上(使用方便,功能少),而后一组类工作在低的层次上(使用麻烦,功能多)。

顺便介绍一个网址:http://tech.ddvip.com/program/ccsharp/base/index.html,里面关于C#的内容不错。

1WebRequest is the abstract base class for the .NET Framework's request/response model for accessing data from the Internet. An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner(协议类型方式), in which the application works with instances of the WebRequest class while protocol-specific descendant classes (子类)carry out the details of the request.

Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.

The WebRequest class throws a WebException when errors occur while accessing an Internet resource. The Status property is one of the WebExceptionStatus values that indicates the source of the error. When Status is WebExceptionStatus..::.ProtocolError, the Response property contains the WebResponse received from the Internet resource.

Because the WebRequest class is an abstract class, the actual behavior of WebRequest instances at run time is determined by the descendant class returned by Create method. For more information about default values and exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.

Note Note:

Use the Create method to initialize new WebRequest instances. Do not use the WebRequest constructor.

Note Note:

If the application that creates the WebRequest object runs with the credentials of a Normal user, the application will not be able to access certificates installed in the local machine store unless permission has been explicitly given to the user to do so.

 

Inheritance Hierarchy (继承方式)

System..::.Object
  System..::.MarshalByRefObject
    
System.Net..::.WebRequest
      System.IO.Packaging..::.PackWebRequest
      System.Net..::.FileWebRequest
      System.Net..::.FtpWebRequest
      System.Net..::.HttpWebRequest

样例:

using System;
  
    
using System.IO;
  
    
using System.Net;
  
    
using System.Text;
  
    
namespace Examples.System.Net
  
    
{    public class WebRequestGetExample
  
    
    {    public static void Main ()
  
    
        {
  
    
            // Create a request for the URL.         
  
    
            WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
  
    
            // If required by the server, set the credentials.
  
    
            request.Credentials = CredentialCache.DefaultCredentials;
  
    
            // Get the response. 通过强制转换由具体的子类来实现具体工作
  
    
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
  
    
            // Display the status.
  
    
            Console.WriteLine (response.StatusDescription);
  
    
            // Get the stream containing content returned by the server.
  
    
            Stream dataStream = response.GetResponseStream ();
  
    
            // Open the stream using a StreamReader for easy access.
  
    
            StreamReader reader = new StreamReader (dataStream);
  
    
            // Read the content.
  
    
            string responseFromServer = reader.ReadToEnd ();
  
    
            // Display the content.
  
    
            Console.WriteLine (responseFromServer);
  
    
            // Cleanup the streams and the response.
  
    
            reader.Close ();
  
    
            dataStream.Close ();
  
    
            response.Close ();
  
    
        }
  
    
    }
  
    
}
  
    

 

2WebResponse Class Provides a response from a Uniform Resource Identifier (URI). This is an abstract class.

The WebResponse class is the abstract base class from which protocol-specific response classes are derived. Applications can participate in request and response transactions in a protocol-agnostic manner using instances of the WebResponse class while protocol-specific classes derived from WebResponse carry out the details of the request.

Client applications do not create WebResponse objects directly; they are created by calling the GetResponse method on a WebRequest instance.

Notes to Inheritors: When you inherit from WebResponse, you must override the following members: ContentLength, ContentType, GetResponseStream, ResponseUri, and Headers.

 

Inheritance Hierarchy (继承关系)

System..::.Object
  System..::.MarshalByRefObject
    
System.Net..::.WebResponse
      System.IO.Packaging..::.PackWebResponse
      System.Net..::.FileWebResponse
      System.Net..::.FtpWebResponse
      System.Net..::.HttpWebResponse

 

3WebClient Class Provides common methods for sending data to and receiving data from a resource identified by a URI.  A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.

Notes to Inheritors Derived classes should call the base class implementation of WebClient to ensure the derived class works as expected.

常用方法:

DownloadFile (String, String)

Downloads the resource with the specified URI to a local file.

DownloadData (String)

Downloads the resource with the specified URI as a Byte array

UploadData

Sends a byte array to the resource and returns a Byte array containing any response

UploadFile

Sends a local file to the resource and returns a Byte array containing any response

 

Inheritance Hierarchy (继承层次)

System.Object
   System.MarshalByRefObject
     System.ComponentModel.Component
      System.Net.WebClient

 

样例:

using System;
  
    
using System.Net;
  
    
using System.IO;
  
    
public class Test
  
    
{
  
    
    public static void Main (string[] args)
  
    
    {
  
    
        if (args == null || args.Length == 0)
  
    
        {
  
    
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
  
    
        }
  
    
        WebClient client = new WebClient ();
  
    
        // Add a user agent header in case the requested URI contains a query.
  
    
        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
  
    
        Stream data = client.OpenRead (args[0]);
  
    
        StreamReader reader = new StreamReader (data);
  
    
        string s = reader.ReadToEnd ();
  
    
        Console.WriteLine (s);
  
    
        data.Close ();
  
    
        reader.Close ();
  
    
    }
  
    
}
  
    

 

你可能感兴趣的:(response)