一、准备数据
API:http://www.weather.com.cn/data/sk/城市ID.html
- 例如,指定获取广州城市的天气
-
API : http://www.weather.com.cn/data/sk/101280101.html
1.Controller层
/**
* 获取天气
* @return null
* @throws Exception
*/
@GetMapping("/farmer/getWeather")
@ApiOperation("获取天气-赣州")
public ResponseResult getWeather() throws Exception {
return orchardJobService.getWeather();
}
2.Service层
/**
* 获取天气
* @return
*/
public ResponseResult getWeather() throws Exception {
ResponseResult responseResult = new ResponseResult();
String weahter;
if (!redisTemplate.hasKey("weather3")) {
URL url = new URL("http://www.weather.com.cn/data/sk/101240701.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, len);
}
inputStream.close();
byteArrayOutputStream.close();
byte[] result = byteArrayOutputStream.toByteArray();
weahter = new String(result, "utf-8");
redisTemplate.opsForValue().set("weather3", weahter, 60 * 60 * 6, TimeUnit.SECONDS);
} else {
//通过键取值
weahter =(String) redisTemplate.opsForValue().get("weather3");
}
return new ResponseResult(weahter);
}
3.预览
http://www.weather.com.cn/data/sk/101240701.html