在C#中,使用HttpWebRequest
類處理HTTP響應(yīng)主要包括以下步驟:
HttpWebRequest
實例:HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "GET"; // 或者 "POST"
request.ContentType = "application/json";
request.Timeout = 10000; // 設(shè)置超時時間(毫秒)
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 處理響應(yīng)的代碼將在這里
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
string responseText = reader.ReadToEnd();
// 處理響應(yīng)文本的代碼將在這里
}
}
下面是一個完整的示例:
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "GET";
request.ContentType = "application/json";
request.Timeout = 10000;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("HTTP狀態(tài)碼: " + response.StatusCode);
Console.WriteLine("HTTP狀態(tài)描述: " + response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
string responseText = reader.ReadToEnd();
Console.WriteLine("響應(yīng)內(nèi)容: " + responseText);
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("請求發(fā)生錯誤: " + ex.Message);
}
}
}
這個示例展示了如何使用HttpWebRequest
類發(fā)送一個GET請求,獲取響應(yīng),并輸出HTTP狀態(tài)碼和響應(yīng)內(nèi)容。你可以根據(jù)實際需求修改這個示例,例如使用POST方法發(fā)送數(shù)據(jù)或處理異常。