项目开发用到数据请求时候,会用的到HttpWebRequest
的请求方式,主要涵盖GET、POST、PUT、DELETE等方法
一、HttpWebRequest简介
HttpWebRequest
是.NET Framework中用于发送HTTP请求的核心类,适用于构建HTTP客户端。它支持GET、POST、PUT、DELETE等HTTP方法,但代码相对底层,需要手动处理请求和响应的生命周期。在.NET Core及后续版本中,推荐使用HttpClient
替代,但本文重点讲解HttpWebRequest
。
二、常用请求方式
1. GET请求(获取资源)
用途:从服务器获取数据(如查询API)。
步骤:
- 创建
HttpWebRequest
实例。 - 设置
Method
为GET
。 - 发送请求并获取响应。
- 读取响应内容。
示例代码:
using System;
using System.IO;
using System.Net;public class HttpGetExample
{public static void Main(){string url = "https://api.example.com/data";try{// 1. 创建请求HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "GET";// 2. 发送请求并获取响应using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){// 3. 读取响应内容using (Stream responseStream = response.GetResponseStream())using (StreamReader reader = new StreamReader(responseStream)){string result = reader.ReadToEnd();Console.WriteLine("Response: " + result);}}}catch (WebException ex){// 异常处理HandleWebException(ex);}}
}
2. POST请求(提交数据)
用途:向服务器提交数据(如表单提交、创建资源)。
步骤:
- 创建请求并设置
Method
为POST
。 - 设置请求头(如
Content-Type
)。 - 写入请求体数据。
- 发送请求并处理响应。
示例代码:
public class HttpPostExample
{public static void Main(){string url = "https://api.example.com/submit";string postData = "username=John&password=123456"; // 表单数据try{// 1. 创建请求HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "POST";request.ContentType = "application/x-www-form-urlencoded"; // 设置内容类型// 2. 写入请求体using (Stream requestStream = request.GetRequestStream())using (StreamWriter writer = new StreamWriter(requestStream)){writer.Write(postData);}// 3. 发送请求并处理响应using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())using (StreamReader reader = new StreamReader(response.GetResponseStream())){string result = reader.ReadToEnd();Console.WriteLine("Response: " + result);}}catch (WebException ex){HandleWebException(ex);}}
}
3. PUT请求(更新资源)
用途:更新服务器上的现有资源(类似POST但用于更新)。
步骤:
- 设置
Method
为PUT
。 - 写入请求体(如JSON或表单数据)。
示例代码:
public class HttpPutExample
{public static void Main(){string url = "https://api.example.com/update/123";string jsonBody = "{\"name\": \"New Name\"}";try{HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "PUT";request.ContentType = "application/json";using (Stream requestStream = request.GetRequestStream())using (StreamWriter writer = new StreamWriter(requestStream)){writer.Write(jsonBody);}using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){Console.WriteLine($"Status Code: {response.StatusCode}");}}catch (WebException ex){HandleWebException(ex);}}
}
4. DELETE请求(删除资源)
用途:删除服务器上的资源。
步骤:
- 设置
Method
为DELETE
。 - 通常不需要请求体,但可以添加查询参数。
示例代码:
public class HttpDeleteExample
{public static void Main(){string url = "https://api.example.com/delete/456";try{HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);request.Method = "DELETE";using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){Console.WriteLine($"Status Code: {response.StatusCode}");}}catch (WebException ex){HandleWebException(ex);}}
}
三、其他常见配置
1. 设置超时
request.Timeout = 5000; // 5秒超时
request.ReadWriteTimeout = 5000; // 读写超时
2. 处理Cookie
// 获取响应中的Cookie
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;// 或者从响应头提取Cookie
foreach (Cookie cookie in response.Cookies)
{Console.WriteLine($"Cookie: {cookie.Name} = {cookie.Value}");
}
3. 设置代理
request.Proxy = new WebProxy("http://proxy.example.com:8080");
4. 处理SSL证书问题(测试环境使用)
ServicePointManager.ServerCertificateValidationCallback +=(sender, certificate, chain, sslPolicyErrors) => true;
四、异步请求
HttpWebRequest
支持异步操作,避免阻塞主线程:
public async Task MakeAsyncRequest()
{HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com");request.Method = "GET";using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())using (Stream stream = response.GetResponseStream())using (StreamReader reader = new StreamReader(stream)){string result = await reader.ReadToEndAsync();Console.WriteLine(result);}
}
五、错误处理与异常管理
HttpWebRequest
通过WebException
抛出异常:
private static void HandleWebException(WebException ex)
{if (ex.Response != null){using (HttpWebResponse errorResponse = (HttpWebResponse)ex.Response){Console.WriteLine($"Error Status Code: {errorResponse.StatusCode}");using (Stream stream = errorResponse.GetResponseStream())using (StreamReader reader = new StreamReader(stream)){Console.WriteLine("Error Response: " + reader.ReadToEnd());}}}else{Console.WriteLine($"Network Error: {ex.Message}");}
}
六、注意事项
- 资源释放:始终使用
using
语句确保WebResponse
和Stream
正确释放。 - 安全性:避免在生产环境忽略SSL证书验证(
ServerCertificateValidationCallback
)。 - 替代方案:在.NET Core中推荐使用
HttpClient
,它更简洁且支持异步操作。 - 性能:频繁请求时,考虑复用
HttpClient
(HttpWebRequest
需手动管理连接池)。
七、总结
HttpWebRequest
是.NET中实现HTTP客户端的基础类,适合需要精细控制请求和响应的场景。但需注意其底层特性及潜在的资源管理问题。对于现代应用,建议优先使用HttpClient
,它提供了更简洁的API和更好的性能。