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:
文章评论