Detailed explanation of the usage of HttpWebRequest in C #

Posted by Phsycoslaya on Sat, 29 Jan 2022 18:02:02 +0100

1. The HttpWebRequest and HttpWebResponse classes are the best choices for sending and receiving HTTP data.

2. Namespace: system Net

3. The HttpWebRequest object was not created using the new keyword (through the constructor).
It is created using the Create() method.

4. You might expect to call a "Send" method explicitly, but you don't.

5. Call Httpwebrequest The getresponse () method returns an HttpWebResponse object

6. You can bind the data stream of the HTTP response to a StreamReader object, and then you can retrieve the entire HTTP response as a string through the ReadToEnd() method. You can also use StreamReader The readline() method retrieves the contents of the HTTP response line by line.

Here are some properties of HttpWebRequest, which are very important for lightweight automated test programs.

a) AllowAutoRedirect: gets or sets a value indicating whether the request should follow the redirect response.
b) Cookie container: gets or sets the cookie associated with this request.
c) Credentials: gets or sets the authentication information for the request.
d) KeepAlive: gets or sets a value indicating whether a persistent connection is established with Internet resources.
e) Maximumautomaticredirects: gets or sets the maximum number of redirects that the request will follow.
f) Proxy: gets or sets the requested proxy information.
g) SendChunked: gets or sets a value indicating whether to send data segments to Internet resources.
h) Timeout: gets or sets the timeout value of the request.
i) UserAgent: gets or sets the value of the user agent HTTP header

C# HttpWebRequest actually submits data in two ways: GET and POST

Role of C# HttpWebRequest:
HttpWebRequest completely encapsulates the HTTP protocol and supports the properties and methods of header, content and cookie in the HTTP protocol. It is easy to write a program to simulate the automatic login of the browser.

C# HttpWebRequest data submission method:
The program uses HTTP protocol to interact with the server, mainly for data submission. Usually, the data submission is completed through GET and POST,

C# HttpWebRequest data submission method

1. GET mode.
The GET method completes the submission of data by attaching parameters to the network address, such as the address http://www.google.com/webhp?hl=zh-CN Middle, front part http://www.google.com/webhp Represents the web address of data submission. The following part hl = zh CN represents additional parameters, where hl represents a key and zh CN represents the value corresponding to this key. The program code is as follows:

HttpWebRequest req =  
(HttpWebRequest)HttpWebRequest.Create("http://www.google.com/webhp?hl=zh-CN" ); 
req.Method = "GET"; 
using (WebResponse wr = req.GetResponse()) 
{ 
   //Here, the received page content is processed 
}

2. POST mode.

POST mode completes data submission by filling in parameters in the page content. The format of parameters is the same as that of GET mode, which is similar to HL = zh CN & newwindow = 1. The program code is as follows:

string param = "hl=zh-CN&newwindow=1";        //parameter
byte[] bs = Encoding.ASCII.GetBytes(param);    //Convert parameters to ascii code
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create("http://www.google. COM / Intl / zh CN / "); / / create request
req.Method = "POST";    //Determine the value transfer method. Here is the value transfer method of post
req.ContentType = "application/x-www-form-urlencoded"; 
req.ContentLength = bs.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //Here, the received page content is processed 
} 

3. Submit Chinese data by GET.

GET mode completes data submission by adding parameters to the network address. For Chinese coding, gb2312 and utf8 are commonly used. The program code accessed by gb2312 coding is as follows:

Encoding myEncoding = Encoding.GetEncoding("gb2312");     //Determine which Chinese coding method to use
string address = "http://www.baidu.com/s?"+ HttpUtility.UrlEncode(" parameter 1 ", myEncoding) +" = "+ httputility. URLEncode (" value 1 ", myEncoding); / / splice the web address of the data submission and the Chinese parameters after Chinese encoding
HttpWebRequest req =   (HttpWebRequest)HttpWebRequest.Create(address);  //Create request
req.Method = "GET";    //Determine the value transfer method. Here is the get method
using (WebResponse wr = req.GetResponse()) 
{ 
   //Here, the received page content is processed 
} 

In the above program code, we access the web address by GET http://www.baidu.com/s , the parameter "parameter 1 = value 1" is passed. Since the other party cannot be informed of the coding type of the submitted data, the coding method should be based on the other party's website. Among the common websites, www.baidu.com The coding method of com (Baidu) is gb2312, www.google.com Com (Google) is encoded in utf8.

4. Submit Chinese data by POST.

The POST method completes the data submission by filling in the parameters in the page content. Since the submitted parameters can explain the coding method used, it can obtain greater compatibility in theory. The program code accessed by gb2312 is as follows:

Encoding myEncoding = Encoding.GetEncoding("gb2312");  //Determine the Chinese coding method. gb2312 is used here
string param =   HttpUtility.UrlEncode("Parameter one", myEncoding) +   "=" + HttpUtility.UrlEncode("Value one", myEncoding) +   "&" +     HttpUtility.UrlEncode("Parameter two", myEncoding) +  "=" + HttpUtility.UrlEncode("Value two", myEncoding); 
byte[] postBytes = Encoding.ASCII.GetBytes(param);     //Convert parameter to assic
HttpWebRequest req = (HttpWebRequest)  HttpWebRequest.Create( "http://www.baidu.com/s" ); 
req.Method = "POST"; 
req.ContentType =   "application/x-www-form-urlencoded;charset=gb2312"; 
req.ContentLength = postBytes.Length; 
using (Stream reqStream = req.GetRequestStream()) 
{ 
   reqStream.Write(bs, 0, bs.Length); 
} 
using (WebResponse wr = req.GetResponse()) 
{ 
   //Here, the received page content is processed 
}  

As can be seen from the above code, when posting Chinese data, first use the UrlEncode method to convert Chinese characters into encoded ASCII code, and then submit it to the server. When submitting, you can explain the encoding method to enable the other server to parse correctly.

The above lists the interaction between the client program and the server using HTTP protocol. The commonly used methods are GET and POST.

Now popular web services also interact through HTTP protocol, using POST method. Slightly different from the above, the data content submitted and received by WebService are encoded in XML. Therefore, HttpWebRequest can also be used when calling WebService.

Here is the basic content of C# HttpWebRequest data submission method. I hope it will be helpful for you to understand and learn C# HttpWebRequest data submission method.

    #region public method
    /// <summary>
    ///Get data interface
    /// </summary>
    ///< param name = "geturl" > interface address < / param >
    /// <returns></returns>
    private static string GetWebRequest(string getUrl)
    {
        string responseContent = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
        request.ContentType = "application/json";
        request.Method = "GET";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //Here, the received page content is processed
        using (Stream resStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
            {
                responseContent = reader.ReadToEnd().ToString();
            }
        }
        return responseContent;
    }
    /// <summary>
    ///Post data interface
    /// </summary>
    ///< param name = "posturl" > interface address < / param >
    ///< param name = "paramdata" > submit json data < / param >
    ///< param name = "dataencode" > encoding method (encoding. Utf8) < / param >
    /// <returns></returns>
    private static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
    {
        string responseContent = string.Empty;
        try
        {
            byte[] byteArray = dataEncode.GetBytes(paramData); //conversion
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            using (Stream reqStream = webReq.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);//Write parameters
                                                                //reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
            {
                //Here, the received page content is processed
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default))
                {
                    responseContent = sr.ReadToEnd().ToString();
                }
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return responseContent;
    }

    #endregion

OAuth head

//Construct OAuth header 
StringBuilder oauthHeader = new StringBuilder();
oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", apiKey);
oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
oauthHeader.AppendFormat("oauth_token={0}", accessToken);

//Construction request 
StringBuilder requestBody = new StringBuilder("");
Encoding encoding = Encoding.GetEncoding("utf-8");
byte[] data = encoding.GetBytes(requestBody.ToString());

// Http Request settings 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Set("Authorization", oauthHeader.ToString());
//request.Headers.Add("Authorization", authorization); 
request.ContentType = "application/atom+xml";
request.Method = "GET";

C # implement http post/get method through WebClient/HttpWebRequest

1.POST method (httpWebRequest)

//body is the parameter to be passed. The format is "roleid = 1 & uid = 2"
//Fill in the cotentType of post: "application/x-www-form-urlencoded"
//soap fill in: "text/xml; charset=utf-8"
public static string PostHttp(string url, string body, string contentType)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

    httpWebRequest.ContentType = contentType;
    httpWebRequest.Method = "POST";
    httpWebRequest.Timeout = 20000;

    byte[] btBodys = Encoding.UTF8.GetBytes(body);
    httpWebRequest.ContentLength = btBodys.Length;
    httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
    string responseContent = streamReader.ReadToEnd();

    httpWebResponse.Close();
    streamReader.Close();
    httpWebRequest.Abort();
    httpWebResponse.Close();

    return responseContent;
}