1.8 微信推送早安及天气预报信息(Springboot框架)(二)

目录

一、搭建框架

1. 环境准备

如果本地没有环境的运行不了代码,需要搭建。
本地环境需要JDK1.8,Tomcat8+,Maven3+。

参考手顺:

2. 搭建Springboot框架

有基础的可以自己快捷搭一个SpringBoot框架,很简单。

推荐用Eclipse或者IDEA开发软件。

也可以在Springboot网站上快捷搭建一个,然后下载到本地使用。

有两个网站可推荐:

  1. Spring Initialize(由Spring官方提供)
    链接: Spring Initialize
    使用教程:Spring 快速入门指南

  2. Aliyun Java Initializr(由阿里云提供)
    链接: Aliyun Java Initializr
    使用教程:与Spring 快速入门指南类似。

不太熟悉Springboot框架的可以参考我之前写的文章。

二、获取代码并完善

1. pom.xml

依赖下载

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lx</groupId>
    <artifactId>wx-push</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>wx-push</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2. application.yml

配置文件

#去申请 https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
wx:
  config:
    #测试号信息
    appId: "wxe5e168f5fb7b34c2"
    appSecret: "daae7a6e9f17881a46420d5e0b481051"
    #模板Id
    templateId: "0aVnDHmeeMwln0muwZv-9_7znO1PzGAvvpsw5GMqa0w"
    #用户列表
    openid: "oTM675yCgD9dNEgV0ll5h37669bY"

message:
  config:
    birthday: "09-03" #生日日期
    togetherDate: "2020-10-11" #填你们在一起的那天日期
    # 改成动态获取早安心语
    # message: "Have a happy day and love you"

#去申请 https://tianqiapi.com/user/login
weather:
  config:
    # not free
    # appid: "xxxxx"
    # appSecret: "xxxxx"
    # free
    unescape: "1"
    version: "v91"
    appid_free: "43656176"
    appsecret_free: "I42og6Lm"
    # dalian 其他参照City.json
    cityid: "101070201"

caihongpi:
  config:
    key: "43495760e2990b2e23fbdc521902dea9"

server:
  port: 8080

3. WxPushApplication.java

Springboot框架启动类

package com.lx.wxpush;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class WxPushApplication {

    public static void main(String[] args) {
        SpringApplication.run(WxPushApplication.class, args);
    }

}

4. wxController.java

控制层代码

这里写的有些乱,感兴趣的可以自己拆分一下。

package com.lx.wxpush.controller;


import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lx.wxpush.utils.CaiHongPiUtils;
import com.lx.wxpush.utils.DateUtil;
import com.lx.wxpush.utils.HttpUtil;

@RestController
@RequestMapping("/wx")
public class wxController {

    @Value("${wx.config.appId}")
    private String appId;
    
    @Value("${wx.config.appSecret}")
    private String appSecret;
    
    @Value("${wx.config.templateId}")
    private String templateId;
    
    @Value("${wx.config.openid}")
    private String openid;
    
	// @Value("${weather.config.appid}")
	// private String weatherAppId;
	// @Value("${weather.config.appSecret}")
	// private String weatherAppSecret;
    
    @Value("${message.config.togetherDate}")
    private String togetherDate;
    
    @Value("${message.config.birthday}")
    private String birthday;
    
    // @Value("${message.config.message}")
    private String message;
    
    @Value("${caihongpi.config.key}")
    private String key;
    
    private String accessToken = "";

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 获取Token
     * 每天早上7:30执行推送
     * @return
     */
    @Scheduled(cron = "0 30 7 ? * *")
    @RequestMapping("/getAccessToken")
    public String getAccessToken() {
        //这里直接写死就可以,不用改,用法可以去看api
        String grant_type = "client_credential";
        //封装请求数据
        String params = "grant_type=" + grant_type + "&secret=" + appSecret + "&appid=" + appId;
        //发送GET请求
        String sendGet = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
        // 解析相应内容(转换成json对象)
        com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(sendGet);
        logger.info("微信token响应结果=" + jsonObject1);
        //拿到accesstoken
        accessToken = (String) jsonObject1.get("access_token");
        return sendWeChatMsg(accessToken);
    }


    /**
     * 发送微信消息
     *
     * @return
     */
    public String sendWeChatMsg(String accessToken) {

        String[] openIds = openid.split(",");
        List<JSONObject> errorList = new ArrayList();
        for (String openId : openIds) {
            JSONObject templateMsg = new JSONObject(new LinkedHashMap<>());

            templateMsg.put("touser", openId);
            templateMsg.put("template_id", templateId);


            JSONObject first = new JSONObject();
            String date = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
            String week = DateUtil.getWeekOfDate(new Date());
            String day = date + " " + week;
            first.put("value", day);
            first.put("color", "#EED016");

            // not free url
            // String TemperatureUrl = "https://www.yiketianqi.com/free/day?appid=" + weatherAppId + "&appsecret=" + weatherAppSecret + "&unescape=1";
            // free url
            String TemperatureUrl = "https://v0.yiketianqi.com/api?unescape=1&version=v91&appid=43656176&appsecret=I42og6Lm&cityid=101070201";
            String sendGet = HttpUtil.sendGet(TemperatureUrl, null);
            JSONObject temperature = JSONObject.parseObject(sendGet);
            JSONArray dataArr = new JSONArray();
            String address = "无法识别"; //城市
            String temHigh = "无法识别"; //最高温度
            String temLow = "无法识别"; //最低温度
            String weatherStatus = "无法识别";//天气状态
            if (temperature.getString("city") != null) {
            	
            	dataArr = temperature.getJSONArray("data"); 
            	temHigh = dataArr.getJSONObject(0).getString("tem1") + "°";
            	temLow = dataArr.getJSONObject(0).getString("tem2") + "°";
                address = temperature.getString("city");
                weatherStatus = dataArr.getJSONObject(0).getString("wea");
                
            }

            JSONObject city = new JSONObject();
            city.put("value", address);
            city.put("color", "#60AEF2");

            String weather = weatherStatus + ", 温度:" + temLow + " ~ " + temHigh;

            JSONObject temperatures = new JSONObject();

            temperatures.put("value", weather);
            temperatures.put("color", "#44B549");

            JSONObject birthDate = new JSONObject();
            String birthDay = "无法识别";
            try {
                Calendar calendar = Calendar.getInstance();
                String newD = calendar.get(Calendar.YEAR) + "-" + birthday;
                birthDay = DateUtil.daysBetween(date, newD);
                if (Integer.parseInt(birthDay) < 0) {
                    Integer newBirthDay = Integer.parseInt(birthDay) + 365;
                    birthDay = newBirthDay + "天";
                } else {
                    birthDay = birthDay + "天";
                }
            } catch (ParseException e) {
                logger.error("togetherDate获取失败" + e.getMessage());
            }
            birthDate.put("value", birthDay);
            birthDate.put("color", "#6EEDE2");


            JSONObject togetherDateObj = new JSONObject();
            String togetherDay = "";
            try {
                togetherDay = "第" + DateUtil.daysBetween(togetherDate, date) + "天";
            } catch (ParseException e) {
                logger.error("togetherDate获取失败" + e.getMessage());
            }
            togetherDateObj.put("value", togetherDay);
            togetherDateObj.put("color", "#FEABB5");

            JSONObject messageObj = new JSONObject();
            
            message = CaiHongPiUtils.getCaiHongPi(key);
            messageObj.put("value", message);
            messageObj.put("color", "#C79AD0");


            JSONObject data = new JSONObject(new LinkedHashMap<>());
            data.put("first", first);
            data.put("city", city);
            data.put("temperature", temperatures);
            data.put("togetherDate", togetherDateObj);
            data.put("birthDate", birthDate);
            data.put("message", messageObj);


            templateMsg.put("data", data);
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

            String sendPost = HttpUtil.sendPost(url, templateMsg.toJSONString());
            JSONObject WeChatMsgResult = JSONObject.parseObject(sendPost);
            if (!"0".equals(WeChatMsgResult.getString("errcode"))) {
                JSONObject error = new JSONObject();
                error.put("openid", openId);
                error.put("errorMessage", WeChatMsgResult.getString("errmsg"));
                errorList.add(error);
            }
            logger.info("sendPost=" + sendPost);
        }
        JSONObject result = new JSONObject();
        result.put("result", "success");
        result.put("errorData", errorList);
        return result.toJSONString();

    }

}

5. CaiHongPiUtil.java

彩虹屁情话语句工具类

package com.lx.wxpush.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author cVzhanshi
 * @create 2022-08-04 22:58
 */
public class CaiHongPiUtils {
	

    public static String getCaiHongPi(String key) {
        String httpUrl = "http://api.tianapi.com/zaoan/index?key=" + key;
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray newslist = jsonObject.getJSONArray("newslist");
        String content = newslist.getJSONObject(0).getString("content");
        return content;
    }

//    public static Map<String,String> getEnsentence() {
//        String httpUrl = "http://api.tianapi.com/zaoan/index?key=43495760e2990b2e23fbdc521902dea9";
//        BufferedReader reader = null;
//        String result = null;
//        StringBuffer sbf = new StringBuffer();
//        try {
//            URL url = new URL(httpUrl);
//            HttpURLConnection connection = (HttpURLConnection) url
//                    .openConnection();
//            connection.setRequestMethod("GET");
//            InputStream is = connection.getInputStream();
//            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
//            String strRead = null;
//            while ((strRead = reader.readLine()) != null) {
//                sbf.append(strRead);
//                sbf.append("\r\n");
//            }
//            reader.close();
//            result = sbf.toString();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        JSONArray newslist = jsonObject.getJSONArray("newslist");
//        String en = newslist.getJSONObject(0).getString("en");
//        String zh = newslist.getJSONObject(0).getString("zh");
//        Map<String, String> map = new HashMap<>();
//        map.put("zh",zh);
//        map.put("en",en);
//        return map;
//    }
}

6. DateUtil.java

时间处理工具类

package com.lx.wxpush.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    /**
     * 将Date对象转换为指定格式的字符串
     *
     * @param date   Date对象
     * @param format 格式化字符串
     * @return Date对象的字符串表达形式
     */
    public static String formatDate(Date date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    /**
     * 根据日期获取星期
     * liuzhu
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    public static String daysBetween(String startDate,String endDate) throws ParseException {
        long nd = 1000 * 24 * 60 * 60;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置时间格式
        Date newStartDate=sdf.parse(startDate);
        Date newEndDate=sdf.parse(endDate);
        long diff = (newEndDate.getTime()) - (newStartDate.getTime()); //计算出毫秒差
        // 计算差多少天
        String day = diff / nd +"";
        return day;
    }


}

7. HttpUtil.java

http请求工具类

package com.lx.wxpush.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {
    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if(param != null) {
            	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;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("Accept", "application/json;charset=UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            conn.connect();
            out = conn.getOutputStream();
            // 发送请求参数
            out.write(param.getBytes("UTF-8"));
            // flush输出流的缓冲
            out.flush();
            out.close();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {

            //System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

8. City.json

城市列表

这个不是很重要,只是为了方便大家查询用到城市的ID,篇幅很长,就不往上贴了。
可以查看以下链接。

国内城市编码表下载

三、 汇总

代码我上传在Gitee,完整框架代码可以去Gitee上下载。

Gitee/ibunsong

OK !

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ibun.song

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

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

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

打赏作者

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

抵扣说明:

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

余额充值