准备工作
公众号必须经过企业认证,个人公众号的无法使用 这是
获取到微信公众号的appId、secret
还有测试的模板
申请之后 每天可以免费调用100次接口,这个Key保存好,一会儿要用
这个Key保存好,一会儿要用
前期工作准备完,正式开始
导入微信推送maven依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.1.0</version>
</dependency>
创建个Util类 WeatherUtil
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class WeatherUtil {
//微信小程序
private static String appId = "你的appId";
private static String secret = "你的secret";
//彩虹屁Key
private static String caiHongPiKey = "你申请的key";
//聚合Key
public static String juHeKey = "你申请的key";
public static void main(String[] args) throws Exception {
getWeather2();
}
/**
* 彩虹屁 https://www.tianapi.com/apiview/181#apicode
* 每天免费获取100次接口调用
* @return 一条彩虹屁的文案
* @throws Exception
*/
public static String caiHongPi() throws Exception {
String tianapi_data = "";
//调用的key
String key = caiHongPiKey;
try {
URL url = new URL( "https://apis.tianapi.com/caihongpi/index?key=" + key);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
OutputStream outputStream = conn.getOutputStream();
outputStream.flush();
outputStream.close();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader (inputStream, StandardCharsets.UTF_8);
BufferedReader bufferedReader = new BufferedReader (inputStreamReader);
StringBuilder tianapi = new StringBuilder();
String temp = null;
while ( null != (temp = bufferedReader.readLine())){
tianapi.append(temp);
}
//结果
tianapi_data = tianapi.toString();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 解析 JSON 响应
JsonObject jsonObject = JsonParser.parseString(tianapi_data).getAsJsonObject();
// 提取 result 对象
JsonObject result = jsonObject.getAsJsonObject("result");
// 获取 city 和 realtime 数据
String content = result.get("content").getAsString();
return content;
}
/**
* 聚合数据,获取天气信息,每天免费调用50次 网址: https://dashboard.juhe.cn/data/index/my
* @return 数据map
* @throws Exception
*/
public static Map<String, String> juHeWeather() throws Exception {
//调用的key
String apiKey = juHeKey;
String apiUrl = "http://apis.juhe.cn/simpleWeather/query";
HashMap<String, String> map = new HashMap<>();
map.put("key", apiKey);
//城市 具体到城市,我家邯郸的,就以邯郸为例了
map.put("city", "邯郸");
URL url = new URL(String.format(apiUrl + "?key=" + apiKey + "&city=邯郸"));
BufferedReader in = new BufferedReader(new InputStreamReader((url.openConnection()).getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 解析 JSON 响应
String jsonResponse = response.toString();
JsonObject jsonObject = JsonParser.parseString(jsonResponse).getAsJsonObject();
// 提取 result 对象
JsonObject result = jsonObject.getAsJsonObject("result");
// 获取 city 和 realtime 数据
String city = result.get("city").getAsString();
JsonObject realtime = result.getAsJsonObject("realtime");
String temperature = realtime.get("temperature").getAsString();
String humidity = realtime.get("humidity").getAsString();
String info = realtime.get("info").getAsString();
String direct = realtime.get("direct").getAsString();
String power = realtime.get("power").getAsString();
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// 正常返回结果,未获取全部信息 {"reason":"查询成功!","result":{"city":"邯郸","realtime":{"temperature":"22","humidity":"29","info":"晴","wid":"00","direct":"东南风","power":"2级","aqi":"43"},"future":[{"date":"2024-10-10","temperature":"13\/22℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"东北风转南风"},{"date":"2024-10-11","temperature":"12\/26℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风转西南风"},{"date":"2024-10-12","temperature":"14\/26℃","weather":"多云转阴","wid":{"day":"01","night":"02"},"direct":"南风"},{"date":"2024-10-13","temperature":"14\/25℃","weather":"多云转晴","wid":{"day":"01","night":"00"},"direct":"南风"},{"date":"2024-10-14","temperature":"13\/28℃","weather":"晴","wid":{"day":"00","night":"00"},"direct":"南风"}]},"error_code":0}
// 打印结果
Map<String,String> resultMap = new HashMap<>();
resultMap.put("today",today);
resultMap.put("city",city);
resultMap.put("temperature",temperature);
resultMap.put("humidity",humidity);
resultMap.put("info",info);
resultMap.put("direct",direct);
resultMap.put("power",power);
return resultMap;
}
/**
* 微信小程序
* @throws Exception
*/
public static void getWeather2() throws Exception {
// 配置微信小程序的配置存储 appid,secret
WxMaDefaultConfigImpl wxMaConfig = new WxMaDefaultConfigImpl();
wxMaConfig.setAppid(appId);
wxMaConfig.setSecret(secret);
// 创建微信小程序服务实例
WxMaService wxMaService = new WxMaServiceImpl();
wxMaService.setWxMaConfig(wxMaConfig);
// 获取 access_token
String accessToken = wxMaService.getAccessToken();
System.out.println("Access Token: " + accessToken);
// 组装要发送的数据
JSONObject body = new JSONObject();
// 要推给谁
body.set("touser", "微信用户id,可以配置多个");
// 模板ID
body.set("template_id", "你申请的模板id");
String content = caiHongPi();
Map<String, String> weatherInfo = juHeWeather();
// 创建消息和内容,这里可以自己定义,对应好模板就行
JSONObject data = new JSONObject();
data.set("today", new JSONObject().set("value", weatherInfo.get("today")));
data.set("city", new JSONObject().set("value", weatherInfo.get("city")));
data.set("temperature", new JSONObject().set("value", weatherInfo.get("temperature")));
data.set("humidity", new JSONObject().set("value",weatherInfo.get("humidity")));
data.set("info", new JSONObject().set("value", weatherInfo.get("info")));
data.set("direct", new JSONObject().set("value", weatherInfo.get("direct")));
data.set("power", new JSONObject().set("value", weatherInfo.get("power")));
data.set("content", new JSONObject().set("value", content));
//上面对应的模板
// 日期:{{today.DATA}}
// 城市:{{city.DATA}}
// 当前温度:{{temperature.DATA}}
// 当前湿度:{{humidity.DATA}}
// 天气信息:{{info.DATA}}
// 风向:{{direct.DATA}}
// 风力:{{power.DATA}}
// 每日一句:{{content.DATA}}
body.set("data", data);
//实现推送到用户消息
String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, body.toString());
//返回内容:{"errcode":0,"errmsg":"ok","msgid":3673554580824145925} 对应的消息id
System.out.println(post);
}
//最后调用 getWeather2() 该方法就🆗了
}
这是调用之后成功推送的效果图:
这是本人的第一篇文章,有不好的地方多多担待。有不懂的欢迎添加我的个人🐧号进行技术讨论,共同进步😊