HttpWebRequest C# Usage Guide

In C#, the HttpWebRequest class is utilized for creating HTTP requests and communicating with web servers. It offers a range of methods and properties for setting request headers, sending requests, and retrieving responses.

Here are some common ways to use HttpWebRequest:

  1. Instantiate an HttpWebRequest object:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
  1. Set the request method:
request.Method = "GET"; // 或者 "POST"
  1. Set the request header:
request.Headers.Add("header-name", "header-value");
  1. Specify the request body (for POST requests):
string postData = "param1=value1&param2=value2";
byte[] requestBody = Encoding.UTF8.GetBytes(postData);
request.ContentLength = requestBody.Length;
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(requestBody, 0, requestBody.Length);
}
  1. Send a request and receive a response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  1. Retrieve response content:
using (Stream responseStream = response.GetResponseStream())
{
    StreamReader reader = new StreamReader(responseStream);
    string responseContent = reader.ReadToEnd();
}
  1. Retrieve response headers:
string responseHeader = response.Headers["header-name"];
  1. Turn off response.
response.Close();

It is worth noting that HttpWebRequest is a implementation of the IDisposable interface, it is recommended to use the using statement to ensure proper release of resources.

The above is the basic usage of HttpWebRequest, you can set other properties or call other methods according to specific needs to achieve more functionality.

bannerAds