Preface
HttpWebRequest is a commonly used class used to send and receive HTTP requests. Using HttpWebRequest in C# can implement various functions, including sending GET and POST requests, processing cookies, setting request headers, adding parameters, etc. This article will introduce the usage of HttpWebRequest in depth and give some common examples.
Table of contents
1. Send a GET request
Sending a GET request using HttpWebRequest is as simple as specifying the target URL. The following is sample code to send a GET request:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string url = "https://www.example.com/api/data";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string responseData = streamReader.ReadToEnd();
Console.WriteLine(responseData);
}
}
}
In the above code, first WebRequest.Create
create an HttpWebRequest
instance through the method and specify the target URL. Then set the request method to GET, GetResponse
send the request through the method and get the response. Finally, StreamReader
the response data is read through the object.
2. Send a POST request
Sending a POST request is similar to sending a GET request. You only need to set the request method to POST and set the data in the request body. Here is sample code to send a POST request:
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
string url = "https://www.example.com/api/data";
string requestData = "param1=value1¶m2=value2";
byte[] byteData = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteData, 0, byteData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string responseData = streamReader.ReadToEnd();
Console.WriteLine(responseData);
}
}
}
In the above code, first convert the request body data into a byte array and set the request method to POST. Then set Content-Type
the header to application/x-www-form-urlencoded
, and set the length of the request body. Then GetRequestStream
obtain the request stream through the method and write the request data into the request stream. The process of sending a request and getting a response is the same as sending a GET request.
3. Set request headers and process cookies
HttpWebRequest also provides some methods and properties to set request headers and handle cookies. The following is sample code for setting request headers and handling cookies:
using System;
using System.IO;
using System.Net;
class Program
{
static void Main()
{
string url = "https://www.example.com/api/data";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
// 设置请求头
request.Headers["Authorization"] = "Bearer xxxxxxx";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36";
// 处理Cookie
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Uri(url), new Cookie("cookie1", "value1"));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string responseData = streamReader.ReadToEnd();
Console.WriteLine(responseData);
}
}
}
In the above code, request.Headers
attributes can be used to set the key-value pairs of the request header. UserAgent
The browser identity of the request can be disguised by setting the attribute. Handle cookies by creating CookieContainer
an object and using Add
methods to add cookies.
4. Add parameters and process responses
When sending a request using HttpWebRequest, you may need to add some parameters and process the response after receiving it. Here is sample code for adding parameters and handling the response:
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
string url = "https://www.example.com/api/data";
string requestData = "param1=value1¶m2=value2";
byte[] byteData = Encoding.UTF8.GetBytes(requestData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteData.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteData, 0, byteData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// 处理响应
HttpStatusCode statusCode = response.StatusCode;
string statusDescription = response.StatusDescription;
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
string responseData = streamReader.ReadToEnd();
Console.WriteLine(responseData);
}
}
}
In the above code, some parameters are added when sending the POST request, and then the status code, status description and response data of the response are obtained.
in conclusion
Use HttpWebRequest in C# to easily send and receive HTTP requests and implement various functions. This article introduces the usage of HttpWebRequest, including sending GET and POST requests, processing cookies, setting request headers, adding parameters, etc. It can be used flexibly as needed to achieve more powerful HTTP request functions. Hope this article is helpful to you!