在C#中,使用HttpWebRequest
类处理HTTP响应主要包括以下步骤:
HttpWebRequest
实例:HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
request.Method = "GET"; // 或者 "POST"
request.ContentType = "application/json";
request.Timeout = 10000; // 设置超时时间(毫秒)
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// 处理响应的代码将在这里
}
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
string responseText = reader.ReadToEnd();
// 处理响应文本的代码将在这里
}
}
下面是一个完整的示例:
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状态码: " + response.StatusCode);
Console.WriteLine("HTTP状态描述: " + response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
{
string responseText = reader.ReadToEnd();
Console.WriteLine("响应内容: " + responseText);
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("请求发生错误: " + ex.Message);
}
}
}
这个示例展示了如何使用HttpWebRequest
类发送一个GET请求,获取响应,并输出HTTP状态码和响应内容。你可以根据实际需求修改这个示例,例如使用POST方法发送数据或处理异常。