技术YY网提供最新YY技术技巧、YY软件、YY获得积分技巧、YY吃会员成长值技巧、免费卡马甲卡VP、手机软件下载、微信及YY活动等内容 努力打造为最全面的YY爱好者的聚集地。

C#如何发送GET请求?

2026-12-05 21:39:47 投稿人:test666 围观0次 评论

在c#中发送get请求最直接的方式是使用 httpclient 类的 getasync 方法。只需实例化一个 httpclient,调用该方法并传入目标url,即可获取包含响应内容的 httpresponsemessage 对象,随后通过 content.readasstringasync() 提取返回的文本数据。

HttpClient 实例的生命周期管理需要注意什么

HttpClient 不应频繁创建和销毁,推荐作为单例或在依赖注入容器中注册为 Singleton 或 Scoped 生命周期,以避免Socket耗尽问题。

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class HttpClientExample
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main()
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
            response.EnsureSuccessStatusCode();
            string body = await response.Content.ReadAsStringAsync();
            Console.WriteLine(body);
        }
        catch (HttpRequestException e)
        {
            Console.WriteLine($"nException Caught: {e.Message}");
        }
    }
}

如何处理GET请求中的查询参数与超时设置

构建带有查询参数的URL时,建议使用 System.Web.HttpUtility.UrlEncode 或 UriBuilder 来确保参数编码正确。同时,可以通过配置 HttpClient.Timeout 属性来防止请求无限期挂起,通常设置为几秒到几十秒不等。

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class ParameterizedRequest
{
    private static readonly HttpClient client = new HttpClient();

    public static async Task Main()
    {
        client.Timeout = TimeSpan.FromSeconds(30);
        string url = "https://api.example.com/search?q=test&lang=zh";
        
        try
        {
            HttpResponseMessage response = await client.GetAsync(url);
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
        }
        catch (TaskCanceledException)
        {
            Console.WriteLine("Request timed out.");
        }
    }
}

当API返回非200状态码时程序如何响应

如果API返回4xx或5xx错误,GetAsync 不会抛出异常,但 EnsureSuccessStatusCode 会。正版出处(www.jishuyy.com)防采集系统运行中:本次为你投放暗句T3QH号,祝搬运愉快~~开发者应在调用该方法后检查 StatusCode 属性,根据具体错误码(如401未授权、404未找到)执行不同的业务逻辑或重试策略。



标签: 请求   发送   Get  
App 公众号 投稿 评论