C# 使用 HttpClient 发送 HTTP POST 请求获取天气信息
C# 使用 HttpClient 发送 HTTP POST 请求获取天气信息
本文介绍使用 C# 中的 HttpClient 发送 HTTP POST 请求,获取天气信息。以下是一个示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class WeatherApiClient
{
private readonly HttpClient _httpClient;
public WeatherApiClient()
{
_httpClient = new HttpClient();
}
public async Task<string> GetWeather(string city)
{
var requestContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>('city', city)
});
var response = await _httpClient.PostAsync('http://api.weatherapi.com/v1/current.json', requestContent);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
public class Program
{
public static async Task Main(string[] args)
{
var weatherApiClient = new WeatherApiClient();
var weather = await weatherApiClient.GetWeather('London');
Console.WriteLine(weather);
}
}
上述代码中,我们创建了一个 WeatherApiClient 类,其中包含一个 GetWeather 方法,该方法接收城市名作为参数,并使用 HttpClient 发送 HTTP POST 请求到天气 API 接口。在 Main 方法中,我们实例化 WeatherApiClient 类并调用 GetWeather 方法获取天气信息,最后将结果打印到控制台上。
注意:
- 上述代码中的天气 API 接口 URL 是一个示例 URL,你需要根据实际情况替换为你所使用的天气 API 接口 URL。
- 另外,还需要根据具体的天气 API 接口要求来构造请求内容和处理返回结果。
原文地址: https://www.cveoy.top/t/topic/pmpG 著作权归作者所有。请勿转载和采集!