項目開發用到數據請求時候,會用的到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和更好的性能。