在C#中,使用WebRequest類可以方便地發起HTTP請求。以下是使用WebRequest類處理HTTP請求的基本步驟:
using System.Net;
using System.IO;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
這里,我們創建了一個指向https://api.example.com/data
的HttpWebRequest實例。你可以根據需要替換為其他URL。
request.Method = "GET"; // 或者 "POST", "PUT", "DELETE" 等
request.Headers["Content-Type"] = "application/json";
request.Headers["Authorization"] = "Bearer your_access_token";
這里,我們設置了請求的內容類型為JSON,并添加了一個授權頭。你可以根據需要設置其他請求頭。
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
這里,我們首先獲取了響應的流,然后使用StreamReader讀取流中的內容并將其轉換為字符串。你可以根據需要處理響應數據。
try
{
// 發起請求和處理響應的代碼
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
}
Console.WriteLine("Error message: {0}", ex.Message);
}
這里,我們使用try-catch語句處理可能發生的WebException異常。在catch塊中,我們可以獲取響應的狀態碼和錯誤消息。
將以上代碼整合在一起,完整的示例如下:
using System;
using System.Net;
using System.IO;
class Program
{
static void Main()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "GET";
request.Headers["Content-Type"] = "application/json";
request.Headers["Authorization"] = "Bearer your_access_token";
try
{
using (Stream responseStream = request.GetResponse().GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseText = reader.ReadToEnd();
Console.WriteLine(responseText);
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
}
Console.WriteLine("Error message: {0}", ex.Message);
}
}
}
請注意替換https://api.example.com/data
和your_access_token
為實際的URL和訪問令牌。