java版微信推送天气信息保姆级教学
微信推送天气信息,使用了vx公众测试号,百度地图天气获取接口(免费),彩虹屁接口(免费),有需要帮助的直接私信。
微信接口测试号
申请网址:https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
里面的appID,appsecret对应程序中的两个变量
public static void main(String[] args) {
push();
}
private static String appId = "";//测试号id
private static String secret‘’ = "";//测试号secret
public static void push(){
//1,配置
WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
wxStorage.setAppId(appId);
wxStorage.setSecret(secret);
WxMpService wxMpService = new WxMpServiceImpl();
wxMpService.setWxMpConfigStorage(wxStorage);
// 推送消息
WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
.toUser("")//用户id
.templateId("")//模板id
.build();
// 配置你的信息
Weather weather = WeatherUtils.getWeather();
templateMessage.addData(new WxMpTemplateData("riqi",weather.getDate() + " "+ weather.getWeek(),"#00BFFF"));
templateMessage.addData(new WxMpTemplateData("tianqi",weather.getText_now(),"#00FFFF"));
templateMessage.addData(new WxMpTemplateData("low",weather.getLow() + "","#173177"));
templateMessage.addData(new WxMpTemplateData("temp",weather.getTemp() + "","#EE212D"));
templateMessage.addData(new WxMpTemplateData("high",weather.getHigh()+ "","#FF6347" ));
templateMessage.addData(new WxMpTemplateData("caihongpi", CaiHongPiUtils.getCaiHongPi(),"#FF69B4"));
templateMessage.addData(new WxMpTemplateData("lianai", JiNianRiUtils.getLianAi()+"","#FF1493"));
templateMessage.addData(new WxMpTemplateData("shengri",JiNianRiUtils.getBirthday_Jo()+"","#FFA500"));
String beizhu = "❤";
if(JiNianRiUtils.getLianAi() % 365 == 0){
beizhu = "今天是恋爱" + (JiNianRiUtils.getLianAi() / 365) + "周年纪念日!";
}
if(JiNianRiUtils.getBirthday_Jo() == 0){
beizhu = "今天是生日,生日快乐呀!";
}
templateMessage.addData(new WxMpTemplateData("beizhu",beizhu,"#FF0000"));
try {
System.out.println(templateMessage.toJson());
System.out.println(wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage));
} catch (Exception e) {
System.out.println("推送失败:" + e.getMessage());
e.printStackTrace();
}
}
创建测试模板:
{{riqi.DATA}} {{beizhu.DATA}} 天气:{{tianqi.DATA}} 最低气温:{{low.DATA}}度 最高气温:{{high.DATA}}度 距离生日还有{{shengri.DATA}}天 每日一句: {{caihongpi.DATA}} {{jinju.DATA}}
到此微信测试号的准备工作已经做好。
百度地图开放平台注册
注册网址:https://lbsyun.baidu.com/
需要创建一个应用,类别选择服务端的就好,记住ak程序中需要使用。
public static Weather getWeather() {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> map = new HashMap<>();
map.put("district_id", "510904");//城市代码
map.put("data_type", "all");
map.put("ak", "");//百度地图接口key
String res = restTemplate.getForObject(
"https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
String.class,
map);
System.out.println(res);
JSONObject json = JSONObject.parseObject(res);
JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
List<Weather> weathers = forecasts.toJavaList(Weather.class);
JSONObject now = json.getJSONObject("result").getJSONObject("now");
Weather weather = weathers.get(0);
weather.setText_now(now.getString("text"));
weather.setTemp(now.getString("temp"));
return weather;
}
彩虹屁注册
网址:https://www.tianapi.com/
里面找到彩虹屁申请接口就好,都是免费的 。
public static String getCaiHongPi() {
String key = "";//彩虹屁接口key
String httpUrl = "http://api.tianapi.com/caihongpi/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 int getLianAi(){
return calculationLianAi("示例2000-01-26");//恋爱日期
}
public static int getBirthday_Jo(){
try {
return calculationBirthday("示例2000-01-25");//生日
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
// 计算生日
public static int calculationBirthday(String clidate) throws ParseException {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar cToday = Calendar.getInstance();
Calendar cBirth = Calendar.getInstance();
cBirth.setTime(myFormatter.parse(clidate));
cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR));
int days;
if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
days += cBirth.get(Calendar.DAY_OF_YEAR);
} else {
days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
}
if (days == 0) {
return 0;
} else {
return days;
}
}
// 计算天数
public static int calculationLianAi(String date) {
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
int day = 0;
try {
long time = System.currentTimeMillis() - simpleDateFormat.parse(date).getTime();
day = (int) (time / 86400000L);
} catch (ParseException e) {
e.printStackTrace();
}
return day;
}
定时任务
@SpringBootApplication
@EnableScheduling//开启定时任务
public class WeatherPushApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherPushApplication.class, args);
}
@Scheduled(cron = "0 0 7 * * ?")//定时早上7点推送
public void push() {
Pusher.push();
}
}
最后上传服务器
直接maven打包成jar包上传到服务器运行就ok了,有不懂的直接私信。
最后返回实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Weather {
private String wd_night;
private String date;
private String high;
private String week;
private String text_night;
private String wd_day;
private String low;
private String wc_night;
private String text_day;
private String wc_day;
// 当前天气
private String text_now;
// 当前温度
String temp;
}