使用 HttpClient 调用 Wea​​therAPI

Posted

技术标签:

【中文标题】使用 HttpClient 调用 Wea​​therAPI【英文标题】:Call WeatherAPI with HttpClient 【发布时间】:2018-09-28 04:33:08 【问题描述】:

我创建了 Web API 来从 OpenWeatherAPI 接收每日温度。 我把API调用放在MVC项目中; (计划稍后创建新项目以获得更好的微服务架构。)

有人在代码中提到:

在您的 HomeController 中,您试图简单地调用操作,就像在 WeatherController 实例上的方法一样。您还需要在那里使用 HttpClient 。另外,不要直接新建 HttpClient。它应该被视为单例

我将如何执行此操作?这是原始代码,一个月前开始编程。

MVC 页面:

namespace WeatherPage.Controllers

    public class HomeController : Controller
    

        public WeatherController weathercontroller = new WeatherController();

        public IActionResult Index()
        
            return View();
        

        public Async Task<IActionResult> About()
        
            ViewData["Message"] = "Your application description page.";
            ViewData["test"] =  weathercontroller.City("Seattle");
            return View();
        
    

API 控制器:

[Route("api/[controller]")] 
public class WeatherController : ControllerBase

    [HttpGet("[action]/city")]
    public async Task<IActionResult> City(string city)
    
        Rootobject rawWeather = new Rootobject();
        using (var client = new HttpClient())
        
            try
            
                client.BaseAddress = new Uri("http://api.openweathermap.org");
                var response = await client.GetAsync($"/data/2.5/weather?q=city&appid=APIkey&units=metric");
                response.EnsureSuccessStatusCode();

                var stringResult = await response.Content.ReadAsStringAsync();
                rawWeather = JsonConvert.DeserializeObject<Rootobject>(stringResult);
                return Ok(rawWeather);
            
            catch (HttpRequestException httpRequestException)
            
                return BadRequest($"Error getting weather from OpenWeather: httpRequestException.Message");
            
        
    
   

public class Rootobject

    public Coord coord  get; set; 
    public Weather[] weather  get; set; 
    public string _base  get; set; 
    public Main main  get; set; 
    public int visibility  get; set; 
    public Wind wind  get; set; 
    public Clouds clouds  get; set; 
    public int dt  get; set; 
    public Sys sys  get; set; 
    public int id  get; set; 
    public string name  get; set; 
    public int cod  get; set; 

这适用于我的项目: https://localhost:55555/api/weather/city/washington

Retrieve Data From Third party Openweather Api

Should We Call Web Api from Mvc Application in Same Solution

【问题讨论】:

【参考方案1】:

这大致意味着你应该使用依赖注入。

    不要在每次需要的时候都创建HttpClient的实例,而是请求HttpClient的实例。 将天气控制器中获取天气的代码提取到服务中,并在天气控制器 api 和家庭控制器中请求该服务

WeatherService

public interface IWeatherService

    Task<Rootobject> CityAsync(string city);


public class WeatherService : IWeatherService
    private HttpClient _httpClient ;
    public WeatherService(IHttpClientFactory clientFactory)
        this._httpClient = clientFactory.CreateClient();
    


    public async Task<Rootobject> CityAsync(string city)
        Rootobject rawWeather = new Rootobject();
        this._httpClient.BaseAddress = new Uri("http://api.openweathermap.org");
        var response = await this._httpClient.GetAsync($"/data/2.5/weather?q=city&appid=APIkey&units=metric");
        response.EnsureSuccessStatusCode();

        var stringResult = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<Rootobject>(stringResult);
    


新的 WeatherController :

[Route("api/[controller]")] 
public class WeatherController : ControllerBase

    private IWeatherService _weatherService;

    public WeatherController(IWeatherService wetherService )
        this._weatherService= wetherService;
    

    [HttpGet("[action]/city")]
    public async Task<IActionResult> City(string city)
    
        try
        
            var rawWeather=await this._weatherService.CityAsync(city);
            return Ok(rawWeather);
        
        catch (HttpRequestException httpRequestException)
        
            return BadRequest($"Error getting weather from OpenWeather: httpRequestException.Message");
        
    

新的 HomeController:

public class HomeController : Controller

    private IWeatherService _weatherService;
    public HomeController(IWeatherService wetherService )
        this._weatherService= wetherService;
    

    public IActionResult Index()
    
        return View();
    

    public async Task<IActionResult> About()
    
        ViewData["Message"] = "Your application description page.";
        ViewData["test"] =  await this._weatherService.CityAsync("Seattle");

        return View();
    


配置服务:

services.AddHttpClient();
services.AddSingleton<IWeatherService ,WeatherService>();

【讨论】:

以上是关于使用 HttpClient 调用 Wea​​therAPI的主要内容,如果未能解决你的问题,请参考以下文章

使用 Wea​​syprint 的 PDF 输出不显示图像(Django)

在 docker (FastAPI) 中使用 Wea​​syPrint 导出的 PDF 中的字体

使用 Wea​​r OS android 拍照

NetCore HttpClient The SSL connection could not be established, see inner exception

HttpClient Received an unexpected EOF or 0 bytes from the transport stream

httpclient失败重连机制