WeatherControllerWeb.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package com.bizmatics.mhfire.controller.web;
  2. import com.bizmatics.common.core.exception.BusinessException;
  3. import com.bizmatics.common.core.util.HttpUtils;
  4. import com.bizmatics.common.core.util.StringUtils;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.io.IOException;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.Map;
  12. /**
  13. * @author yq
  14. * @date 2021/6/16 18:02
  15. */
  16. @RestController
  17. @RequestMapping("aliWeather")
  18. public class WeatherControllerWeb {
  19. private static final String ALI_WEATHER_API_URL = "https://weather01.market.alicloudapi.com/area-to-weather?area=闵行区";
  20. private static final String ALI_WEATHER_HEADER_KEY = "Authorization";
  21. private static final String ALI_WEATHER_APPCODE = "0f2b7fce6e104ba8835358b7b59b4fb6";
  22. private static final String ALI_WEATHER_HEADER_VALUE = "APPCODE " + ALI_WEATHER_APPCODE;
  23. private String weather = "";
  24. private Date date = null;
  25. @GetMapping()
  26. public String get() {
  27. if (StringUtils.isBlank(weather)){
  28. weather = getWeatherApi();
  29. date = new Date();
  30. }else {
  31. if ((System.currentTimeMillis() - date.getTime()) >= (1000 * 60 * 60 * 5)){
  32. weather = getWeatherApi();
  33. date = new Date();
  34. }
  35. }
  36. return weather;
  37. }
  38. public String getWeatherApi(){
  39. try {
  40. Map<String,String> headerMap = new HashMap<>();
  41. headerMap.put(ALI_WEATHER_HEADER_KEY,ALI_WEATHER_HEADER_VALUE);
  42. return HttpUtils.get(ALI_WEATHER_API_URL,headerMap);
  43. } catch (IOException e) {
  44. throw new BusinessException(e.getMessage());
  45. }
  46. }
  47. }