Java 实现天气预报

效果图

1、登录高德地图API开放平台

天气查询-API文档-开发指南-Web服务 API | 高德地图API

2、用户在高德地图官网申请web服务API类型KEY

 

 

3、天气查询

天气查询API服务地址:

URL

https://restapi.amap.com/v3/weather/weatherInfo?parameters

请求方式

GET

parameters代表的参数包括必填参数和可选参数。所有参数均使用和号字符(&)进行分隔。下面的列表枚举了这些参数及其使用规则。 

  • 请求参数

参数名

含义

规则说明

是否必须

缺省值

key

请求服务权限标识

用户在高德地图官网申请web服务API类型KEY

必填

city

城市编码

输入城市的adcode,adcode信息可参考城市编码表

必填

extensions

气象类型

可选值:base/all

base:返回实况天气

all:返回预报天气

可选

output

返回格式

可选值:JSON,XML

可选

JSON

  • 返回结果参数说明

实况天气每小时更新多次,预报天气每天更新3次,分别在8、11、18点左右更新。由于天气数据的特殊性以及数据更新的持续性,无法确定精确的更新时间,请以接口返回数据的reporttime字段为准。天气结果对照表>>

名称

含义

规则说明

status

返回状态

值为0或1

1:成功;0:失败

count

返回结果总数目

info

返回的状态信息

infocode

返回状态说明,10000代表正确

lives

实况天气数据信息

province

省份名

city

城市名

adcode

区域编码

weather

天气现象(汉字描述)

temperature

实时气温,单位:摄氏度

winddirection

风向描述

windpower

风力级别,单位:级

humidity

空气湿度

reporttime

数据发布的时间

forecast

预报天气信息数据

city

城市名称

adcode

城市编码

province

省份名称

reporttime

预报发布时间

casts

预报数据list结构,元素cast,按顺序为当天、第二天、第三天的预报数据

date

日期

week

星期几

dayweather

白天天气现象

nightweather

晚上天气现象

daytemp

白天温度

nighttemp

晚上温度

daywind

白天风向

nightwind

晚上风向

daypower

白天风力

nightpower

晚上风力

4、测试获取杭州天气

api:https://restapi.amap.com/v3/weather/weatherInfo?key=你的key&city=330900

5、搭建对应的数据库表,字段要与json中的一一对应

 6、创建与表对应实体类

/**
 * TbHkhb:天气表
 * @author zyw
 * @since 2022-03-19 13:42:24
 */
@Data
@ApiModel(value="天气表,对应表tb_weather",description="适用于新增和修改页面传参")
public class TbWeather extends ProBaseEntity<TbWeather> {
    private static final long serialVersionUID = -89506524104887138L;
    /**
     * 主键id
     */
    @ApiModelProperty(value="主键id")
    private String id;
    /**
     * 日期
     */
    @ApiModelProperty(value="日期")
    private Date date;
    /**
     * 星期几
     */
    @ApiModelProperty(value="星期几")
    private String week;
    /**
     * 白天天气现象
     */
    @ApiModelProperty(value="白天天气现象")
    private String dayweather;
    /**
     * 晚上天气现象
     */
    @ApiModelProperty(value="晚上天气现象")
    private String nightweather;
    /**
     * 白天温度
     */
    @ApiModelProperty(value="白天温度")
    private String daytemp;
    /**
     * 晚上温度
     */
    @ApiModelProperty(value="晚上温度")
    private String nighttemp;
    /**
     * 白天风向
     */
    @ApiModelProperty(value="白天风向")
    private String daywind;
    /**
     * 晚上风向
     */
    @ApiModelProperty(value="晚上风向")
    private String nightwind;
    /**
     * 白天风力
     */
    @ApiModelProperty(value="白天风力")
    private String daypower;
    /**
     * 晚上风力
     */
    @ApiModelProperty(value="晚上风力")
    private String nightpower;

}

7、编写获取天气信息的业务逻辑

主要思想:

  1. 获取实时时间,根据当下时间获取所需要天气预报的时间范围;
  2. 通过API获取JSON格式的天气数据;
  3. 解析JSON格式,转换为字符串,再从字符串中分解出字符数组;
  4. 将其中的值分割出来,赋值给对应的对象属性;
  5. 设置定时任务,每次存入数据库之前,清除根据时间范围清除数据库中旧的天气预报信息;
  6. 批量新增最新的天气预报信息
    /**
     * TbZbzsService: 天气表 业务实现类
     *  开发注意:
     *      1. 增/删/改 方法需要进行事务注解(@Transactional);
     *      2. service中有异常则直接向外抛出;
     * @author zyw
     * @date 2022-03-19 13:55:31
     **/
    @Service
    public class TbWeatherService extends ProBaseService<TbWeatherDao, TbWeather> {
    
        private  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        /**
         * @方法名称: getWeather
         * @实现功能: 获取最新的天气预报 TODO: 方法入参根据页面对象设置
         * @create by zyw at 2022-03-19 17:12:31
         **/
        public List<TbWeather> getWeather(){
            Date date = new Date();
    
            Calendar rightSmall = Calendar.getInstance();
            Calendar rightBig = Calendar.getInstance();
            rightSmall.setTime(date);
            rightBig.setTime(date);
    
            rightSmall.add(Calendar.DAY_OF_YEAR,-3);//日期减3天
            rightBig.add(Calendar.DAY_OF_YEAR,2);//日期加2天
    
            return dao.getNewWeather(rightSmall.getTime(), rightBig.getTime());
    
        }
    
    
        /**
         * @方法名称: importWeather
         * @实现功能: 定时存入实时天气预报 TODO: 方法入参根据页面对象设置
         * @create by zyw at 2022-03-19 14:04:31
         **/
    //        @Scheduled(cron = "0/3 * * * * ?") //表达式只能写6位
    //    @Scheduled(cron = "0 0 */1 * * ?")    //每小时
        @Scheduled(cron = "0 0 1 * * ?")    //每天凌晨1点执行一次
        public void importWeather(){
            System.out.println("~~~~~~~~定时存入实时天气预报~~~~~~~~~~");
            String requestURL = "https://restapi.amap.com/v3/weather/weatherInfo?parameters&key=你的key&city=330900&extensions=all&output=JSON";
    
    
            HttpURLConnection conn = null;
            BufferedReader reader = null;
    //使用免费api查询天气,请求数据时需要提交的参数
            Map<String, String> params = new HashMap();
            StringBuilder stringBuilder = new StringBuilder();
    
            try {
                //存储返回结果
                String strRead = null;
                //开始连接
                URL url = new URL(requestURL);
                conn = (HttpURLConnection) url.openConnection();
                //使用Get方式请求数据
                conn.setRequestMethod("GET");
                conn.connect();
                //输入流获取返回数据
                InputStream is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    
                while ((strRead = reader.readLine()) != null) {
                    stringBuilder.append(strRead);
                }
    
                JSONObject jsonObject = JSON.parseObject(stringBuilder.toString());
    
                String casts = (jsonObject.getJSONArray("forecasts")).toString().substring(1, (jsonObject.getJSONArray("forecasts")).toString().length() - 1);
    
                List<TbWeather> tbWeathers = JSON.parseObject((JSON.parseObject(casts)).getJSONArray("casts").toJSONString(), new TypeReference<List<TbWeather>>() {
                });
                for (TbWeather tbWeather : tbWeathers) {
                    tbWeather.setId(UUID.randomUUID().toString().replace("-", "").substring(0, 20));
                    tbWeather.setCreateDate(new Date());
                }
    
    
                Date date = new Date();
                //清除数据库中存储的旧的天气预报
                Calendar rightSmall = Calendar.getInstance();
                Calendar rightBig = Calendar.getInstance();
                rightSmall.setTime(date);
                rightBig.setTime(date);
    
                rightSmall.add(Calendar.DAY_OF_YEAR,-1);//日期减1天
                rightBig.add(Calendar.DAY_OF_YEAR,3);//日期加2天
    
                int dates = dao.deleteWeatherByDates(rightSmall.getTime(),rightBig.getTime());
                System.out.println("清除"+dates+"条旧天气数据");
    
                int i = dao.insertTbWeatherList(tbWeathers);
                System.out.println("添加" + i+"条天气数据");
    
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
    
            }
    
        }
    }

    <!--批量新增-->
    <insert id="insertTbWeatherList"  parameterType="java.util.List">
        insert into tb_weather (
        id,
        date,
        week,
        dayweather,
        nightweather,
        daytemp,
        nighttemp,
        daywind,
        nightwind,
        daypower,
        nightpower,
        create_date
        ) VALUES
        <foreach collection="list" item="item" separator=",">
            (
            #{item.id},
            #{item.date},
            #{item.week},
            #{item.dayweather},
            #{item.nightweather},
            #{item.daytemp},
            #{item.nighttemp},
            #{item.daywind},
            #{item.nightwind},
            #{item.daypower},
            #{item.nightpower},
            #{item.createDate}
            )
        </foreach>
    </insert>

<!--    删除指定时间范围内的-->
    <delete id="deleteWeatherByDates" parameterType="com.hlframe.intControl.entity.TbWeather">
        DELETE	from tb_weather
        where (date &gt;= #{yesterday} and date &lt; #{dayAfterTomorrow})
    </delete>

8、前端调用获取实时天气预报

获取前端所需要的时间范围,根据时间范围查找数据库中的天气预报数据

    private  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * @方法名称: getWeather
     * @实现功能: 获取最新的天气预报 TODO: 方法入参根据页面对象设置
     * @create by zyw at 2022-03-19 17:12:31
     **/
    public List<TbWeather> getWeather(){
        Date date = new Date();

        Calendar rightSmall = Calendar.getInstance();
        Calendar rightBig = Calendar.getInstance();
        rightSmall.setTime(date);
        rightBig.setTime(date);

        rightSmall.add(Calendar.DAY_OF_YEAR,-3);//日期减3天
        rightBig.add(Calendar.DAY_OF_YEAR,2);//日期加2天

        return dao.getNewWeather(rightSmall.getTime(), rightBig.getTime());

    }
    <select id="getNewWeather" resultType="com.hlframe.intControl.entity.TbWeather">
        select
        <include refid="TbHkhbColumns"/>
        from tb_weather a
        <include refid="TbHkhbJoins"/>
        <where>
            date &gt;= #{smallDate}
            and date &lt;= #{bigDate}
        </where>
        order by create_date
    </select>

    /**
     * @方法名称: getWeather
     * @实现功能: 获取实时最新天气预报, TODO: 方法入参根据页面对象设置
     * @return  java.lang.String
     * @create by zyw at 2022-03-19 17:32:26
     **/
    @ApiOperation(value="获取实时最新天气预报",notes="返回全部数据后端接口",response = TbWeather.class)
    @PostMapping(value = "/getWeather")
    public String getWeather(){
        try {
            return buildResultStr(buildSuccessResultData(service.getWeather(), TbWeather.class));
        } catch (Exception e) {
            logError(log, e);
            return buildResultStr(buildErrorResultData(e.getMessage()));
        }
    }

9、效果图

  • 18
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柚几哥哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值