C# 结合 Javascript 测试获取天气信息
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
public class WeatherFetcher
{
private static readonly HttpClient _httpClient = new HttpClient();
public static async Task<string> GetWeatherInformation(string city)
{
// 替换为你的 API 密钥
const string openWeatherMapApiKey = "YOUR_OPEN_WEATHER_MAP_API_KEY";
string url = $"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={openWeatherMapApiKey}&units=metric";
try
{
HttpResponseMessage response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
// 使用示例
public class Program
{
public static async Task Main(string[] args)
{
string city = "London";
string weatherInformation = await WeatherFetcher.GetWeatherInformation(city);
Console.WriteLine(weatherInformation);
// 解析天气信息为 JSON 对象
JObject jsonResponse = JObject.Parse(weatherInformation);
Console.WriteLine($"Temperature: {jsonResponse["main"]["temp"]}°C");
Console.WriteLine($"Description: {jsonResponse["weather"][0]["description"]}");
}
}
在这个代码示例中,我们定义了一个WeatherFetcher
类,它包含了一个异步方法GetWeatherInformation
,该方法使用HttpClient
从OpenWeatherMap API获取天气信息。然后在Main
方法中,我们等待获取天气信息并打印出来。我们还演示了如何解析JSON以提取特定的信息,例如温度和天气描述。这个示例展示了如何在C#中进行HTTP请求和JSON处理,这对于开发Web应用是非常有用的技能。
评论已关闭