【六袆-Java】springboot调用中国天气第三方接口;获取指定城市的天气;存储在redis里面;
一、准备数据
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

本文来自博客园,作者:你好,Alf,转载请注明原文链接:https://www.cnblogs.com/Alf-/p/16192848.html

浙公网安备 33010602011771号