JAVA获取天气情况功能实现
package com.tydt.utils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tydt.entity.po.TydtWeather;
import com.tydt.service.ITydtWeatherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
//定时任务工具类
@Component
public class WeatherToolsUtils {
protected final Logger logger = LoggerFactory.getLogger(WeatherToolsUtils.class);
@Autowired
private ITydtWeatherService service;
@Scheduled(cron = "0 5 0 * * ?") // 每天凌晨12点05分执行
public void runTask() {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
// 构建URL
String city = "根据实际更改";
String appid = "根据实际更改";
String appsecret = "根据实际更改";
String hours = "根据实际更改";
//API文档如下 start
//http://www.tianqiapi.com/index/doc?version=2030
//API文档如上 end
String urlString = "http://v0.yiketianqi.com/free/v2030" +
"?city=" + URLEncoder.encode(city, "UTF-8") +
"&appid=" + URLEncoder.encode(appid, "UTF-8") +
"&appsecret=" + URLEncoder.encode(appsecret, "UTF-8") +
"&hours=" + URLEncoder.encode(hours, "UTF-8");
URL url = new URL(urlString);
// 打开连接
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// 读取返回数据
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
logger.info("天气预报返回信息:" + response.toString());
if (response.length() > 0) {
//字段多得话可以json转实体类保存
TydtWeather tydtWeather = new TydtWeather();
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(response.toString());
String date = jsonNode.get("date").asText();
String wea = jsonNode.get("wea").asText();
String temperatureMax = jsonNode.get("tem1").asText();
String temperatureMin = jsonNode.get("tem2").asText();
String windDirection = jsonNode.get("win").asText();
String windSpeed = jsonNode.get("win_speed").asText();
String windMeter = jsonNode.get("win_meter").asText();
String humidity = jsonNode.get("humidity").asText();
String visibility = jsonNode.get("visibility").asText();
String pressure = jsonNode.get("pressure").asText();
JsonNode alarms = jsonNode.get("alarm");
if (alarms.isArray()) {
for (JsonNode alarm : alarms) {
String alarmType = alarm.get("alarm_type").asText();
String alarmLevel = alarm.get("alarm_level").asText();
String alarmTitle = alarm.get("alarm_title").asText();
String alarmContent = alarm.get("alarm_content").asText();
tydtWeather.setAlarmType(alarmType);
tydtWeather.setAlarmLevel(alarmLevel);
tydtWeather.setAlarmTitle(alarmTitle);
tydtWeather.setAlarmContent(alarmContent);
}
}
JsonNode hour = jsonNode.get("hours");
tydtWeather.setDate(date);
tydtWeather.setWea(wea);
tydtWeather.setTem1(temperatureMax);
tydtWeather.setTem2(temperatureMin);
tydtWeather.setWin(windDirection);
tydtWeather.setWinSpeed(windSpeed);
tydtWeather.setWinMeter(windMeter);
tydtWeather.setHumidity(humidity);
tydtWeather.setVisibility(visibility);
tydtWeather.setPressure(pressure);
tydtWeather.setCreateTime(new Date());
//24小时趋势,将json保存到一个字段中,mysql数据库字段类型为json。后续查看详情接口进行转换
tydtWeather.setHours(hour.toString());
service.insertTydtWeather(tydtWeather);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("获取天气预报异常" + e.getMessage());
} finally {
// 关闭连接和读取器
if (conn != null) {
conn.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package com.tydt.entity.po;
import com.tydt.core.entity.BaseEntity;
import lombok.Data;
import java.util.List;
/**
* 天气对象 tydt_weather
*
* @author tydt
* @date 2024-06-27
*/
@Data
public class TydtWeather extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* $column.columnComment
*/
private Long id;
/**
* $column.columnComment
*/
private String date;
/**
* $column.columnComment
*/
private String wea;
/**
* $column.columnComment
*/
private String tem1;
/**
* $column.columnComment
*/
private String tem2;
/**
* $column.columnComment
*/
private String win;
/**
* $column.columnComment
*/
private String winSpeed;
/**
* $column.columnComment
*/
private String winMeter;
/**
* $column.columnComment
*/
private String humidity;
/**
* $column.columnComment
*/
private String visibility;
/**
* $column.columnComment
*/
private String pressure;
/**
* $column.columnComment
*/
private String alarmType;
/**
* $column.columnComment
*/
private String alarmLevel;
/**
* $column.columnComment
*/
private String alarmTitle;
/**
* $column.columnComment
*/
private String alarmContent;
private String hours;
private List<Hours> hoursList;
}
package com.tydt.entity.po;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Hours {
private String hours;
private String tem;
}
@Override
public TydtWeather selectTydtWeatherById(Long id)
{
TydtWeather tydtWeather = tydtWeatherMapper.selectTydtWeatherById(id);
//转json
if(tydtWeather!=null && StringUtils.isNotBlank(tydtWeather.getHours())){
try {
ObjectMapper objectMapper = new ObjectMapper();
List<Hours> hoursList = Arrays.asList(objectMapper.readValue(tydtWeather.getHours(), Hours[].class));
tydtWeather.setHoursList(hoursList);
}catch (Exception e){
e.printStackTrace();
}
}
return tydtWeather;
}