温馨提示×

c# httpwebrequest如何发送GET请求

c#
小樊
82
2024-11-16 20:31:51
栏目: 编程语言

在C#中,您可以使用HttpWebRequest类发送GET请求。以下是一个简单的示例,说明如何使用HttpWebRequest发送GET请求并获取响应:

using System;
using System.IO;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        // 目标URL
        string url = "https://api.example.com/data";

        // 创建HttpWebRequest实例
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        // 设置请求方法为GET
        request.Method = "GET";

        // 设置请求头(可选)
        request.Headers["Accept"] = "application/json";

        try
        {
            // 发送请求并获取响应
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                // 获取响应状态码
                int statusCode = response.StatusCode;
                Console.WriteLine("Response Status Code: " + statusCode);

                // 读取响应内容
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string responseContent = reader.ReadToEnd();
                    Console.WriteLine("Response Content: " + responseContent);
                }
            }
        }
        catch (WebException ex)
        {
            // 处理异常
            using (WebResponse response = ex.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                int statusCode = httpResponse.StatusCode;
                Console.WriteLine("Error: " + statusCode);
            }
        }
    }
}

在这个示例中,我们首先创建一个HttpWebRequest实例,并将其目标URL设置为https://api.example.com/data。然后,我们将请求方法设置为GET,并可选地设置请求头。接下来,我们发送请求并获取响应,然后读取响应内容并将其输出到控制台。如果在发送请求时发生异常,我们将捕获该异常并输出错误状态码。

0