C# 调用restful api

本文详细介绍了如何在C#应用程序中利用HttpClient类来调用RESTful API,包括设置请求头、发送GET和POST请求,以及处理响应数据。通过实例代码,帮助开发者理解API交互过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public string getUrlJson(string url)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.ContentType = "application/json;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string json = getResponseString(response);
                return json;
            }
            catch (Exception e)
            {
                throw;
            }


        }
        private static string getResponseString(HttpWebResponse response)
        {
            string json = null;
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")))
            {
                json = reader.ReadToEnd();
            }
            return json;
        }


C# 中,调用 RESTful API 的过程通常涉及以下几个步骤: 1. **添加依赖**:首先,你需要在项目中添加对 `System.Net.Http` 或 `HttpClientFactory` 的引用,这两个库提供了处理 HTTP 请求的功能。 ```csharp using System.Net.Http; ``` 2. **创建 HttpClient 实例**:通过 `HttpClient` 类实例化一个新的客户端对象,这是发送请求的基础。 ```csharp HttpClient client = new HttpClient(); ``` 3. **构建请求**:确定你要请求的 URL、HTTP 方法(GET、POST、PUT等)、所需的参数(如果有的话)。例如,发送 GET 请求: ```csharp string url = "https://api.example.com/resource"; Uri uri = new Uri(url); HttpContent content = null; HttpResponseMessage response = await client.GetAsync(uri, content); ``` 4. **处理响应**:检查响应状态码,成功则读取响应内容,一般使用 `response.IsSuccessStatusCode` 和 `.Content.ReadAsStringAsync()`。 ```csharp if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); // 这里处理返回的数据 } else { // 处理错误 } ``` 5. **异常处理**:考虑到网络连接不稳定或其他不可预见的情况,需要捕获并处理可能出现的异常。 6. **使用 async/await**:为了提高性能,对于耗时操作(如网络请求),C# 提供了异步编程模型,使用 `async` 和 `await` 可以避免阻塞主线程。 ```csharp public async Task<string> GetResource() { try { return await client.GetStringAsync(url); } catch (Exception ex) { // log or handle the exception return ""; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值