继C++中使用cpp-httplib和nlohmann_json库实现http请求获取天气数据和Nodejs通过get请求获取api.open-meteo.com网站的天气数据、使用Java通过get请求获取api.open-meteo.com网站的天气数据、Python中通过get请求获取api.open-meteo.com网站的天气数据,我们再使用C#语言实现对应功能。
以下是使用 C# 发送 HTTP GET 请求以获取 api.open-meteo.com 网站天气数据的示例代码:
示例代码
csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// API URL
string url = "http://api.open-meteo.com/v1/forecast";
string latitude = "37.8136"; // 纬度
string longitude = "144.9631"; // 经度
// 构造查询参数
string query = $"?latitude={latitude}&longitude={longitude}¤t_weather=true";
try
{
// 使用 HttpClient 发送 GET 请求
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url + query);
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine("Weather Data:");
Console.WriteLine(responseData);
}
else
{
Console.WriteLine($"Failed to retrieve data. Status code: {response.StatusCode}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
说明
-
HttpClient:
- 使用
HttpClient类发送 HTTP GET 请求。 GetAsync方法用于异步发送 GET 请求。
- 使用
-
API URL 和查询参数:
- 基础 URL 为
http://api.open-meteo.com/v1/forecast。 - 查询参数包括:
latitude:纬度。longitude:经度。current_weather=true:请求当前天气数据。
- 基础 URL 为
-
响应处理:
- 使用
response.IsSuccessStatusCode检查响应是否成功。 - 使用
response.Content.ReadAsStringAsync()异步读取响应内容。
- 使用
-
异常处理:
- 捕获网络错误或其他异常,并打印错误信息。
运行代码
-
创建项目
在终端中运行以下命令创建一个新的 C# 控制台项目:
bashdotnet new console -n GetWeatherData cd GetWeatherData -
替换代码
将上述代码粘贴到
Program.cs文件中。 -
运行程序
在终端中运行以下命令:
bashdotnet run
示例输出
plaintext
Weather Data:
{
"latitude": 37.8136,
"longitude": 144.9631,
"generationtime_ms": 0.123,
"utc_offset_seconds": 0,
"timezone": "GMT",
"current_weather": {
"temperature": 20.5,
"windspeed": 5.2,
"winddirection": 180
}
}
注意事项
-
确保你的网络可以访问
http://api.open-meteo.com。 -
如果需要解析 JSON 响应,可以使用
System.Text.Json或Newtonsoft.Json库。例如:csharpvar weatherData = JsonSerializer.Deserialize<WeatherResponse>(responseData); Console.WriteLine($"Temperature: {weatherData.CurrentWeather.Temperature}"); -
如果需要更复杂的功能(如 POST 请求或认证),可以扩展代码。