目录
一、搭建框架
1. 环境准备
如果本地没有环境的运行不了代码,需要搭建。 本地环境需要JDK1.8,Tomcat8+,Maven3+。
参考手顺:
2. 搭建Springboot框架
有基础的可以自己快捷搭一个SpringBoot框架,很简单。
推荐用Eclipse或者IDEA开发软件。
也可以在Springboot网站上快捷搭建一个,然后下载到本地使用。
有两个网站可推荐:
-
Spring Initialize(由Spring官方提供) 链接: Spring Initialize 使用教程:Spring 快速入门指南 -
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/>
</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
配置文件
wx:
config:
appId: "wxe5e168f5fb7b34c2"
appSecret: "daae7a6e9f17881a46420d5e0b481051"
templateId: "0aVnDHmeeMwln0muwZv-9_7znO1PzGAvvpsw5GMqa0w"
openid: "oTM675yCgD9dNEgV0ll5h37669bY"
message:
config:
birthday: "09-03"
togetherDate: "2020-10-11"
weather:
config:
unescape: "1"
version: "v91"
appid_free: "43656176"
appsecret_free: "I42og6Lm"
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("${message.config.togetherDate}")
private String togetherDate;
@Value("${message.config.birthday}")
private String birthday;
private String message;
@Value("${caihongpi.config.key}")
private String key;
private String accessToken = "";
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Scheduled(cron = "0 30 7 ? * *")
@RequestMapping("/getAccessToken")
public String getAccessToken() {
String grant_type = "client_credential";
String params = "grant_type=" + grant_type + "&secret=" + appSecret + "&appid=" + appId;
String sendGet = HttpUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token", params);
com.alibaba.fastjson.JSONObject jsonObject1 = com.alibaba.fastjson.JSONObject.parseObject(sendGet);
logger.info("微信token响应结果=" + jsonObject1);
accessToken = (String) jsonObject1.get("access_token");
return sendWeChatMsg(accessToken);
}
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");
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;
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;
}
}
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 {
public static String formatDate(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
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 {
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);
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));
}
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 {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param) {
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new 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)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
out = conn.getOutputStream();
out.write(param.getBytes("UTF-8"));
out.flush();
out.close();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}
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 !
|