pom.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/controller/WeatherController.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/dto/weather/Weather.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/dto/weather/WeatherInfo.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/dto/weather/WeatherInfo2.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/mapper/WeatherCityMapper.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/pojo/WeatherCity.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/service/WeatherService.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/java/com/whyc/util/HttpUtil.java | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
src/main/resources/mapper/WeatherCityMapper.xml | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
pom.xml
@@ -45,6 +45,12 @@ <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.springframework.boot</groupId> src/main/java/com/whyc/controller/WeatherController.java
New file @@ -0,0 +1,19 @@ package com.whyc.controller; import com.whyc.dto.Response; import io.swagger.annotations.Api; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("weather") @Api(tags = "天气查询") @Slf4j public class WeatherController { public Response get(){ return null; } } src/main/java/com/whyc/dto/weather/Weather.java
New file @@ -0,0 +1,51 @@ package com.whyc.dto.weather; import java.util.List; public class Weather { private Integer id; /** * 实时-聚合和百度共用字段 */ private WeatherInfo realtime; /** * 未来天气-聚合 */ private List<WeatherInfo> future; /** * 未来天气-百度 */ private List<WeatherInfo2> future2; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public WeatherInfo getRealtime() { return realtime; } public void setRealtime(WeatherInfo realtime) { this.realtime = realtime; } public List<WeatherInfo> getFuture() { return future; } public void setFuture(List<WeatherInfo> future) { this.future = future; } public List<WeatherInfo2> getFuture2() { return future2; } public void setFuture2(List<WeatherInfo2> future2) { this.future2 = future2; } } src/main/java/com/whyc/dto/weather/WeatherInfo.java
New file @@ -0,0 +1,96 @@ package com.whyc.dto.weather; import java.util.Date; public class WeatherInfo { /**日期*/ private Date date; /**温度*/ private String temperature; /**湿度*/ private String humidity; /**天气*/ private String info; /**天气ID*/ private String wid; /**风向*/ private String direct; /**风力*/ private String power; /**空气质量*/ private String aqi; /**未来天气*/ private String weather; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getHumidity() { return humidity; } public void setHumidity(String humidity) { this.humidity = humidity; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getWid() { return wid; } public void setWid(String wid) { this.wid = wid; } public String getDirect() { return direct; } public void setDirect(String direct) { this.direct = direct; } public String getPower() { return power; } public void setPower(String power) { this.power = power; } public String getAqi() { return aqi; } public void setAqi(String aqi) { this.aqi = aqi; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } } src/main/java/com/whyc/dto/weather/WeatherInfo2.java
New file @@ -0,0 +1,108 @@ package com.whyc.dto.weather; /** * 天气信息-预报-百度天气专用 */ public class WeatherInfo2 { /**白天天气*/ private String infoDay; /**晚上天气*/ private String infoNight; /**最高温度*/ private Integer temperatureHigh; /**最低温度*/ private Integer temperatureLow; /**白天风力*/ private String powerDay; /**晚上风力*/ private String powerNight; /**白天风向*/ private String directDay; /**晚上风向*/ private String directNight; /**星期*/ private String week; /**日期*/ private String date; public String getInfoDay() { return infoDay; } public void setInfoDay(String infoDay) { this.infoDay = infoDay; } public String getInfoNight() { return infoNight; } public void setInfoNight(String infoNight) { this.infoNight = infoNight; } public Integer getTemperatureHigh() { return temperatureHigh; } public void setTemperatureHigh(Integer temperatureHigh) { this.temperatureHigh = temperatureHigh; } public Integer getTemperatureLow() { return temperatureLow; } public void setTemperatureLow(Integer temperatureLow) { this.temperatureLow = temperatureLow; } public String getPowerDay() { return powerDay; } public void setPowerDay(String powerDay) { this.powerDay = powerDay; } public String getPowerNight() { return powerNight; } public void setPowerNight(String powerNight) { this.powerNight = powerNight; } public String getDirectDay() { return directDay; } public void setDirectDay(String directDay) { this.directDay = directDay; } public String getDirectNight() { return directNight; } public void setDirectNight(String directNight) { this.directNight = directNight; } public String getWeek() { return week; } public void setWeek(String week) { this.week = week; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } } src/main/java/com/whyc/mapper/WeatherCityMapper.java
New file @@ -0,0 +1,13 @@ package com.whyc.mapper; import com.whyc.pojo.WeatherCity; import org.apache.ibatis.annotations.Param; import java.util.List; public interface WeatherCityMapper extends CustomMapper<WeatherCity> { WeatherCity getWeatherCity2(@Param("city")WeatherCity city); WeatherCity getWeatherCity(@Param("city")WeatherCity city); } src/main/java/com/whyc/pojo/WeatherCity.java
New file @@ -0,0 +1,14 @@ package com.whyc.pojo; import lombok.Data; /** * 天气支持查询的城市 */ @Data public class WeatherCity { private Integer id; private String province; private String city; private String district; } src/main/java/com/whyc/service/WeatherService.java
New file @@ -0,0 +1,213 @@ package com.whyc.service; import com.whyc.dto.Response; import com.whyc.dto.weather.Weather; import com.whyc.dto.weather.WeatherInfo; import com.whyc.dto.weather.WeatherInfo2; import com.whyc.mapper.WeatherCityMapper; import com.whyc.pojo.WeatherCity; import com.whyc.util.ActionUtil; import com.whyc.util.HttpUtil; import net.sf.ezmorph.object.DateMorpher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.util.JSONUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import javax.servlet.ServletContext; import java.util.*; import static com.whyc.util.HttpUtil.urlencode; @Service public class WeatherService { /**属于第三方-聚合的天气接口*/ // 天气情况查询接口地址 private static String API_URL = "http://apis.juhe.cn/simpleWeather/query"; // 接口请求Key private static String API_KEY = "d88bb2c73f4fa5d1c0fee1df0b5d108a"; /**属于第三方-百度的天气接口*/ private static String API_URL_BAIDU = "https://api.map.baidu.com/weather/v1/"; private static String API_KEY_BAIDU = "tcnlFtekhszWP65H14Mzvhd10uwZVW6G"; @Resource private WeatherCityMapper weatherCityMapper; /**百度天气查询使用*/ public Response get2(WeatherCity city) { Response model = new Response(); //调试用 //city.setId(1); List<WeatherInfo2> futureList = new LinkedList<>(); WeatherInfo realtime = new WeatherInfo(); //根据传过来的省市区,定位到区码cityId Integer cityId = getId2(city); if(cityId==0){ model.setMsg("暂不支持当前城市天气查询"); }else { //首先从ApplicationContext中获取,如果不存在,则请求第三方接口,同时将值存入 ServletContext application = ActionUtil.getApplication(); List<Weather> weatherList = (List<Weather>) application.getAttribute("weather"); if (weatherList == null) { weatherList = new ArrayList<>(); /*//调试 Weather weather = new Weather(); weather.setId(2); weather.setRealtime(new WeatherInfo()); weatherList.add(weather);*/ } //List<Weather> weatherList = new ArrayList<>(); //weatherList.addAll(weatherList2); if (weatherList.size() == 0) { Map<String, Object> params = new HashMap<>();//组合参数 params.put("district_id", cityId); params.put("data_type", "all"); params.put("ak", API_KEY_BAIDU); String queryParams = urlencode(params); String response = HttpUtil.doGet(API_URL_BAIDU, queryParams); try { JSONObject jsonObject = JSONObject.fromObject(response); int error_code = jsonObject.getInt("status"); if (error_code == 0) { JSONObject result = jsonObject.getJSONObject("result"); JSONObject realtimeJson = result.getJSONObject("now"); JSONArray futureJsonArr = result.getJSONArray("forecasts"); JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd", "yyyy-MM-dd"})); realtime.setTemperature(String.valueOf(realtimeJson.getInt("temp"))); realtime.setPower(realtimeJson.getString("wind_class")); realtime.setDirect(realtimeJson.getString("wind_dir")); realtime.setInfo(realtimeJson.getString("text")); for (int i = 0; i < futureJsonArr.size(); i++) { WeatherInfo2 futureInfo = new WeatherInfo2(); JSONObject futureJson = futureJsonArr.getJSONObject(i); futureInfo.setTemperatureHigh(futureJson.getInt("high")); futureInfo.setTemperatureLow(futureJson.getInt("low")); futureInfo.setPowerDay(futureJson.getString("wc_day")); futureInfo.setPowerNight(futureJson.getString("wc_night")); futureInfo.setDirectDay(futureJson.getString("wd_day")); futureInfo.setDirectNight(futureJson.getString("wd_night")); futureInfo.setInfoDay(futureJson.getString("text_day")); futureInfo.setInfoNight(futureJson.getString("text_night")); futureInfo.setWeek(futureJson.getString("week")); futureInfo.setDate(futureJson.getString("date")); futureList.add(futureInfo); } model.setCode(1); model.setData(realtime); model.setData2(futureList); System.out.println("调用第三方接口取,并存入内存"); //将值存入到application中 Weather weatherTemp = new Weather(); weatherTemp.setId(cityId); weatherTemp.setRealtime(realtime); weatherTemp.setFuture2(futureList); weatherList.add(weatherTemp); application.setAttribute("weather", weatherList); } else { model.setMsg("天气查询接口失败:" + jsonObject.getString("message")); } } catch (Exception e) { e.printStackTrace(); model.setMsg("接口异常"); } } else { for (int i = 0; i < weatherList.size(); i++) { if(weatherList.get(i).getId().intValue()==cityId){ model.setCode(1); model.setData(weatherList.get(i).getRealtime()); model.setData2(weatherList.get(i).getFuture2()); System.out.println("从内存中取"); return model; } } Map<String, Object> params = new HashMap<>();//组合参数 params.put("district_id", cityId); params.put("data_type", "all"); params.put("ak", API_KEY_BAIDU); String queryParams = urlencode(params); String response = HttpUtil.doGet(API_URL_BAIDU, queryParams); try { JSONObject jsonObject = JSONObject.fromObject(response); int error_code = jsonObject.getInt("status"); if (error_code == 0) { JSONObject result = jsonObject.getJSONObject("result"); JSONObject realtimeJson = result.getJSONObject("now"); JSONArray futureJsonArr = result.getJSONArray("forecasts"); JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[]{"yyyy-MM-dd", "yyyy-MM-dd"})); realtime.setTemperature(String.valueOf(realtimeJson.getInt("temp"))); realtime.setPower(realtimeJson.getString("wind_class")); realtime.setDirect(realtimeJson.getString("wind_dir")); realtime.setInfo(realtimeJson.getString("text")); for (int i = 0; i < futureJsonArr.size(); i++) { WeatherInfo2 futureInfo = new WeatherInfo2(); JSONObject futureJson = futureJsonArr.getJSONObject(i); futureInfo.setTemperatureHigh(futureJson.getInt("high")); futureInfo.setTemperatureLow(futureJson.getInt("low")); futureInfo.setPowerDay(futureJson.getString("wc_day")); futureInfo.setPowerNight(futureJson.getString("wc_night")); futureInfo.setDirectDay(futureJson.getString("wd_day")); futureInfo.setDirectNight(futureJson.getString("wd_night")); futureInfo.setInfoDay(futureJson.getString("text_day")); futureInfo.setInfoNight(futureJson.getString("text_night")); futureInfo.setWeek(futureJson.getString("week")); futureInfo.setDate(futureJson.getString("date")); futureList.add(futureInfo); } model.setCode(1); model.setData(realtime); model.setData2(futureList); System.out.println("调用第三方接口取,并存入内存"); //将值存入到application中 Weather weatherTemp = new Weather(); weatherTemp.setId(cityId); weatherTemp.setRealtime(realtime); weatherTemp.setFuture2(futureList); weatherList.add(weatherTemp); application.setAttribute("weather", weatherList); } else { model.setMsg("天气查询接口失败:" + jsonObject.getString("message")); } } catch (Exception e) { e.printStackTrace(); model.setMsg("接口异常"); } } } return model; } public Integer getId2(WeatherCity city){ WeatherCity weatherCity = weatherCityMapper.getWeatherCity2(city); if (weatherCity==null){ WeatherCity weatherCity1 = weatherCityMapper.getWeatherCity(city); if (weatherCity1==null){ return 0; }else { return weatherCity1.getId(); } }else{ return weatherCity.getId(); } } } src/main/java/com/whyc/util/HttpUtil.java
New file @@ -0,0 +1,221 @@ package com.whyc.util; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; /** * */ public class HttpUtil { public static final String VIDEO_URL = "https://open.ys7.com/api/lapp/token/get"; public static final String VIDEO_REQUEST_BODY = "appKey=07457eaa64a546a2bb016635fe1e744d&appSecret=8438b941b7e129e2ba0689759326ad56"; public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 /*for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); }*/ // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * get方式的http请求 * * @param httpUrl 请求地址 * @return 返回结果 */ public static String doGet(String httpUrl, String queryParams) { HttpURLConnection connection = null; InputStream inputStream = null; BufferedReader bufferedReader = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString()); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:get connection.setRequestMethod("GET"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(5000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(6000); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); // 封装输入流,并指定字符集 bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = bufferedReader.readLine()) != null) { sbf.append(temp); sbf.append(System.getProperty("line.separator")); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != bufferedReader) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != inputStream) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect();// 关闭远程连接 } } return result; } /** * post方式的http请求 * * @param httpUrl 请求地址 * @return 返回结果 */ public static String doPost(String httpUrl,String requestBody) { HttpURLConnection connection = null; InputStream inputStream = null; BufferedReader bufferedReader = null; String result = null;// 返回结果字符串 try { // 创建远程url连接对象 URL url = new URL(new StringBuffer(httpUrl).toString()); // 通过远程url连接对象打开一个连接,强转成httpURLConnection类 connection = (HttpURLConnection) url.openConnection(); // 设置连接方式:post connection.setRequestMethod("POST"); // 设置连接主机服务器的超时时间:15000毫秒 connection.setConnectTimeout(5000); // 设置读取远程返回的数据时间:60000毫秒 connection.setReadTimeout(6000); //请求体 connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(outputStream,"UTF-8"); osw.write(requestBody); osw.flush(); outputStream.close(); // 发送请求 connection.connect(); // 通过connection连接,获取输入流 if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); // 封装输入流,并指定字符集 bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // 存放数据 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = bufferedReader.readLine()) != null) { sbf.append(temp); sbf.append(System.getProperty("line.separator")); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != bufferedReader) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != inputStream) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect();// 关闭远程连接 } } return result; } /** * 将map型转为请求参数型 * * @param data * @return */ public static String urlencode(Map<String, ?> data) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, ?> i : data.entrySet()) { try { sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } String result = sb.toString(); result = result.substring(0, result.lastIndexOf("&")); return result; } } src/main/resources/mapper/WeatherCityMapper.xml
New file @@ -0,0 +1,37 @@ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.whyc.mapper.WeatherCityMapper" > <select id="getWeatherCity2" resultType="com.whyc.pojo.WeatherCity" parameterType="com.whyc.pojo.WeatherCity"> select district_code from web_site.tb_weather_city2 <where> <if test="city.province !=null and city.province !='' and city.province!='null'"> and province like CONCAT('%',#{city.province},'%' </if> <if test="city.city !=null and city.city !='' and city.city!='null'"> and city like CONCAT('%',#{city.city},'%' </if> <if test="city.district !=null and city.district !='' and city.district!='null'"> and district like CONCAT('%',#{city.district},'%' </if> </where> limit 1 </select> <select id="getWeatherCity" resultType="com.whyc.pojo.WeatherCity" parameterType="com.whyc.pojo.WeatherCity"> select district_code from web_site.tb_weather_city <where> <if test="city.province !=null and city.province !='' and city.province!='null'"> and province like CONCAT('%',#{city.province},'%' </if> <if test="city.city !=null and city.city !='' and city.city!='null'"> and city like CONCAT('%',#{city.city},'%' </if> <if test="city.district !=null and city.district !='' and city.district!='null'"> and district like CONCAT('%',#{city.district},'%' </if> </where> limit 1 </select> </mapper>