C# HttpWebRequest Notes

2019年12月15日 3589点热度 0人点赞 3条评论
内容目录

Table of Contents:

 

1. HttpWebRequest Instantiation

2. GetResponse to Retrieve Request Results

3. Retrieve Results

4. Get Stream Information

 

HttpWebRequest is an HTTP request class that inherits from WebRequest.

WebRequest is an abstract class that can issue requests to a Uniform Resource Identifier (URI).

WebRequest has the following derived classes:

 

  • System.IO.Packaging.PackWebRequest
  • System.Net.FileWebRequest
  • System.Net.FtpWebRequest
  • System.Net.HttpWebRequest

Usage:

using System.Net;

1. HttpWebRequest Instantiation

The following is the instantiation method. When writing code in Visual Studio, you will be prompted to simplify the code for the reasons explained below.

            string url = "http://baidu.com";
            HttpWebRequest httpWeb = (HttpWebRequest)HttpWebRequest.Create(url);

HttpWebRequest corresponds to the URL, so its connection string must be a valid HTTP string, and must start with the HTTP protocol type.

It can be:

  • http:// 
  • https:// 

 You can include a port:

http://baidu.com:666

It can also be an IP, but you must include the HTTP header and port.

The HttpWebRequest object is instantiated generally not by using new directly, but by using the .Create method to return a WebRequest object.

HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create("https://www.whuanle.cn:443");

Note the following two methods:

HttpWebRequest.Create
WebRequest.Create

Create returns a WebRequest object as Create is a static method.

        public static WebRequest Create(string requestUriString);
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> WebRequest Create(Uri requestUri);

    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> WebRequest CreateDefault(Uri requestUri);</pre>

So when creating an HttpWebRequest instance, you would do:

HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create("https://www.whuanle.cn:443");

 

HttpWebRequest supports both GET and POST methods for requests,

Setting method:

            HttpWebRequest httpWeb = (HttpWebRequest)WebRequest.Create("https://www.whuanle.cn:443");
            httpWeb.Method = "GET";

 

The request types of WebRequest.

  • http://

  • https://

  • ftp://

  • file://

2. GetResponse to Retrieve Request Results

The HttpWebRequest object uses the .GetResponse() method to retrieve the return result. The .GetResponse() returns a WebResponse object.

Methods of the WebResponse object:

Close()

When overridden by a derived class, it closes the response stream.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy for communication with a remote object.

(Inherited from MarshalByRefObject)

Dispose()

Releases the unmanaged resources used by the WebResponse object.

Dispose(Boolean)

Releases the unmanaged resources used by the WebResponse object and optionally releases the managed resources.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)

GetHashCode()

Acts as the default hash function.

(Inherited from Object)

GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)

GetObjectData(SerializationInfo, StreamingContext)     

Populates a SerializationInfo with the data needed to serialize the target object.

GetResponseStream()

When overridden in a derived class, returns the data stream from the internet resource.

GetType()

Gets the Type of the current instance.

(Inherited from Object)

InitializeLifetimeService()

Obtains a lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)

MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)

ToString()

Returns a string that represents the current object.

3. Getting Results

Use the GetResponseStream() method of the WebSponse object to obtain the data stream.

                string Url = "https://www.whuanle.cn:443";
                WebRequest wReq = WebRequest.Create(Url);
                WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();

 

4. Getting Stream Information

                string Url = "https://www.whuanle.cn:443";
                WebRequest wReq = WebRequest.Create(Url);
                WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.UTF8))
                {
                    string a = "";
                    while ((a = reader.ReadLine()) != null)
                    {
                        Console.WriteLine(a);
                    }
                    return reader.ReadToEnd();
                }

The above is an example of obtaining a stream, outputting it using UTF8 encoding and reading it line by line.

Here is another method:

                string Url = "https://www.whuanle.cn:443";
                WebRequest wReq = WebRequest.Create(Url);
                WebResponse wResp = wReq.GetResponse();
                System.IO.Stream respStream = wResp.GetResponseStream();

                using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, Encoding.UTF8))
                {
                    string str = reader.ReadToEnd();
                    Console.WriteLine(str);
                }

Using reader.ReadToEnd() allows you to read all characters from the stream at once.

 
---------------------------
Recommended reading: another article that lists all methods, properties, etc., of objects like WebRequest, WebResponse.
Address:
 

痴者工良

高级程序员劝退师

文章评论