Kaynağa Gözat

天气预告相关接口开发

jichaobo 2 yıl önce
ebeveyn
işleme
7f7f18b329

+ 58 - 0
service-fire/service-fire-biz/src/main/java/com/usky/fire/controller/web/WeatherControllerWeb.java

@@ -0,0 +1,58 @@
+package com.usky.fire.controller.web;
+
+
+import com.alibaba.nacos.common.utils.StringUtils;
+import com.usky.common.core.exception.BusinessException;
+import com.usky.common.core.util.HttpUtils;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author yq
+ * @date 2021/6/16 18:02
+ */
+@RestController
+@RequestMapping("aliWeather")
+public class WeatherControllerWeb {
+
+
+    private static final String ALI_WEATHER_API_URL = "https://weather01.market.alicloudapi.com/area-to-weather?area=闵行区";
+    private static final String ALI_WEATHER_HEADER_KEY = "Authorization";
+    private static final String ALI_WEATHER_APPCODE = "0f2b7fce6e104ba8835358b7b59b4fb6";
+    private static final String ALI_WEATHER_HEADER_VALUE = "APPCODE " + ALI_WEATHER_APPCODE;
+
+    private String weather = "";
+
+    private Date date = null;
+
+    @GetMapping()
+    public String get() {
+        if (StringUtils.isBlank(weather)) {
+            weather = getWeatherApi();
+            date = new Date();
+        } else {
+            if ((System.currentTimeMillis() - date.getTime()) >= (1000 * 60 * 60 * 5)) {
+                weather = getWeatherApi();
+                date = new Date();
+            }
+        }
+        return weather;
+    }
+
+    public String getWeatherApi() {
+        try {
+            Map<String, String> headerMap = new HashMap<>();
+            headerMap.put(ALI_WEATHER_HEADER_KEY, ALI_WEATHER_HEADER_VALUE);
+            return HttpUtils.get(ALI_WEATHER_API_URL, headerMap);
+        } catch (IOException e) {
+            throw new BusinessException(e.getMessage());
+        }
+    }
+}
+