Browse Source

阿里云天气接口

yq 4 years ago
parent
commit
b6f0fe7c70

+ 62 - 0
mhfire-controller/src/main/java/com/bizmatics/mhfire/controller/web/WeatherControllerWeb.java

@@ -0,0 +1,62 @@
+package com.bizmatics.mhfire.controller.web;
+
+
+
+
+import com.bizmatics.common.core.exception.BusinessException;
+import com.bizmatics.common.core.util.HttpUtils;
+
+
+import com.bizmatics.common.core.util.StringUtils;
+import okhttp3.*;
+
+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;
+
+/**
+ * @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)){
+                weather = getWeatherApi();
+                date = new Date();
+            }
+        }
+        return weather;
+    }
+    public String getWeatherApi(){
+        try {
+            OkHttpClient defaultClient = HttpUtils.getDefaultClient();
+            Request request1 = new Request.Builder().url(ALI_WEATHER_API_URL).addHeader(ALI_WEATHER_HEADER_KEY,ALI_WEATHER_HEADER_VALUE).build();
+            Response response = defaultClient.newCall(request1).execute();
+            return HttpUtils.responseToString(response);
+        } catch (IOException e) {
+            throw new BusinessException(e.getMessage());
+        }
+    }
+}
+