北屋教程网

专注编程知识分享,从入门到精通的编程学习平台

C#调用第三方API的实战示例_c# 第三方

一、准备工作

1. 安装依赖包

使用NuGet安装Newtonsoft.Json(JSON解析)和System.Net.Http(HTTP客户端):

bash

Install-Package Newtonsoft.Json

Install-Package System.Net.Http


2. 创建HttpClient实例

建议单例模式复用HttpClient,避免频繁创建导致的Socket耗尽问题:

public static readonly HttpClient client = new HttpClient();


二、GET请求示例(以天气API为例)


using System.Net.Http;

using Newtonsoft.Json;


public class WeatherResponse

{

public string City { get; set; }

public double Temperature { get; set; }

}


public async Task<WeatherResponse> GetWeatherAsync(string city)

{

string url = #34;https://api.weather.example.com?city={city}";

try

{

HttpResponseMessage response = await client.GetAsync(url);


response.EnsureSuccessStatusCode(); // 检查HTTP状态码

string responseBody = await response.Content.ReadAsStringAsync();

return JsonConvert.DeserializeObject<WeatherResponse>(responseBody);

}

catch (HttpRequestException ex)

{

Console.WriteLine(#34;请求失败: {ex.Message}");

return null;

}

}


关键点:

- 使用EnsureSuccessStatusCode()自动抛出非2xx状态码异常

- 异步方法避免阻塞主线程


三、POST请求示例(以用户登录为例)


public class LoginRequest

{

public string Username { get; set; }

public string Password { get; set; }

}


public class LoginResponse

{

public string Token { get; set; }

public DateTime Expires { get; set; }

}


public async Task<LoginResponse> LoginAsync(string username, string password)

{

var request = new LoginRequest { Username = username, Password = password };

var jsonContent = JsonConvert.SerializeObject(request);

using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))

{

HttpResponseMessage response = await client.PostAsync("https://api.auth.example.com/login", content);

string responseBody = await response.Content.ReadAsStringAsync();

if (response.IsSuccessStatusCode)

return JsonConvert.DeserializeObject<LoginResponse>(responseBody);

else

throw new HttpRequestException(#34;API返回错误: {responseBody}");

}

}


关键点:

- 使用StringContent封装JSON请求体

- 手动检查响应状态码并处理错误


四、异常处理与性能优化

1. 常见异常类型

- HttpRequestException:网络错误、DNS解析失败

- TaskCanceledException:超时或请求取消

- JsonException:JSON解析失败


2. 优化建议

- 设置超时时间:client.Timeout = TimeSpan.FromSeconds(30);

- 使用HttpClientFactory替代单例模式(.NET Core推荐)

- 添加重试逻辑(如 Polly 库)


五、注意事项

1. API文档依赖

- 必须根据目标API的文档调整:

- 请求头(如Authorization、Content-Type)

- 参数格式(URL参数/Body参数)

- 认证方式(API Key/OAuth2等)


2. 安全建议

- 敏感信息(如API密钥)应通过配置文件或环境变量管理

- 对HTTPS请求启用证书验证(默认已开启)

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言