温馨提示×

c# httpwebrequest如何处理响应

c#
小樊
81
2024-11-16 20:33:52
栏目: 编程语言

在C#中,使用HttpWebRequest类处理HTTP响应主要包括以下步骤:

  1. 创建一个HttpWebRequest实例:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.example.com/data");
  1. 设置请求属性(可选):
request.Method = "GET"; // 或者 "POST"
request.ContentType = "application/json";
request.Timeout = 10000; // 设置超时时间(毫秒)
  1. 发送请求并获取响应:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    // 处理响应的代码将在这里
}
  1. 读取响应内容(可选):
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方法发送数据或处理异常。

0