七夕送礼物-程序员也可以假浪漫

一直看python可以定时发微信消息,天气预报、小故事、情话什么的;上网搜有没有java版本的,下下来玩一玩,谁知道没有找到,只好自己写一个了,由于这是个自娱自乐的小程序,就没有这么多代码规范,大家莫嫌弃,上代码:

码云地址:

https://gitee.com/dzx201314/autoSendTianqi.git

程序使用spring boot 2.0.8 结构为:

一、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 http://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.0.8.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.tianqi</groupId>
	<artifactId>autoSendTianqi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>autoSendTianqi</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-web</artifactId>
		</dependency>

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

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<!--Lombok -->
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		
		<dependency>
			<groupId>com.github.qcloudsms</groupId>
			<artifactId>qcloudsms</artifactId>
			<version>1.0.6</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName><!--打jar包去掉版本号 -->
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

二、核心类:TianqiController.java

package com.tianqi.autoSendTianqi.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.tianqi.autoSendTianqi.util.HttpUtils;
import com.tianqi.autoSendTianqi.util.MailUtils;
import com.tianqi.autoSendTianqi.vo.Friend;
import com.tianqi.autoSendTianqi.vo.FriendList;
import com.tianqi.autoSendTianqi.vo.Tianqi;
import com.tianqi.autoSendTianqi.vo.Tianqi.WeatherBeanX;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class TianqiController {
	@Autowired
	private MailUtils mail;
	
	@Scheduled(cron = "45 59 8 ? * *")
	public void find() {
		String url = "http://tq.360.cn/api/weatherquery/querys?app=tq360&code=101020100&t=201565159968966&c=201565260989066";
		String json = HttpUtils.httpGet(url);
		json = json.substring(9, json.length() - 1);
		Tianqi tianqi = JSON.parseObject(json, Tianqi.class);
		List<Friend> fs = FriendList.getFriends();
		
		sendPhone(tianqi, fs);
		
		sendMail(tianqi, fs);
	}

	@GetMapping("tianqi")
	public void find1() {
		String url = "http://tq.360.cn/api/weatherquery/querys?app=tq360&code=101020100&t=201565159968966&c=201565260989066";
		String json = HttpUtils.httpGet(url);
		json = json.substring(9, json.length() - 1);
		log.info(json);
		Tianqi tianqi = JSON.parseObject(json, Tianqi.class);
		List<Friend> fs = FriendList.getFriends();
		
		sendMail(tianqi, fs);
	}
	
	/**
	 * <p><b>Title:</b> sendMail</p>
	 * <p><b>Description:</b> </p>
	 * @author douzi
	 * @param tianqi
	 * @param fs
	 */
	private void sendMail(Tianqi tianqi, List<Friend> fs) {
		String result = getResult(tianqi);
		log.info(result);
		String curr = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date());
		fs.forEach(f -> {
			if (StringUtils.isNotBlank(f.getEmail())) {
				mail.sendSimpleMail(f.getEmail(),  curr + "天气怎么样?", result);
			}
		});
	}

	/**
	 * <p><b>Title:</b> sendPhone</p>
	 * <p><b>Description:</b> </p>
	 * @author douzi
	 * @param tianqi
	 * @param fs
	 */
	private void sendPhone(Tianqi tianqi, List<Friend> fs) {
		ArrayList<String> result1 = getResult1(tianqi);
		try {
                        //此处参数为腾讯短信平台的appid 和 key,需要短信的朋友请自行申请并且参考文档
			SmsSingleSender ssender = new SmsSingleSender(XXXXXXXX, "XXXXXXXXXXXXXXXXXXXXXXXXXX");
			
			for (Friend f : fs) {
				if (StringUtils.isNotBlank(f.getPhone())) {
					SmsSingleSenderResult result2 = ssender.sendWithParam("86", f.getPhone(),
							391359, result1, null, "", "");
					log.info(result2 + "");
				}
			}
		} catch (HTTPException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		String curr = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss").format(new Date());
		System.out.println(curr);
	}

	/**
	 * <p><b>Title:</b> getResult</p>
	 * <p><b>Description:</b> 生成发送字符串</p>
	 * @author douzi
	 * @param tianqi
	 * @return
	 */
	private String getResult(Tianqi tianqi) {
		String city = tianqi.getArea().get(0).get(0);
		String pm = tianqi.getPm25().getAdvice();
		String temperature = tianqi.getRealtime().getWeather().getTemperature();
		String direct = tianqi.getRealtime().getWind().getDirect();
		String info = tianqi.getRealtime().getWeather().getInfo();
		String wendu = "";
		List<WeatherBeanX> weather = tianqi.getWeather();
		for (WeatherBeanX w : weather) {
			if (w.getDate().equals(tianqi.getRealtime().getDate())) {
				wendu += w.getInfo().getNight().get(2);
				wendu += "℃  ~ ";
				wendu += w.getInfo().getDay().get(2) + "℃";
				break;
			}
		}
		String chuanyi = tianqi.getLife().getInfo().getChuanyi().get(1);
		String tiexin = tianqi.getLife().getInfo().getDaisan().get(1);
		String yundong = tianqi.getLife().getInfo().getYundong().get(1);
		String ziwaixian = tianqi.getLife().getInfo().getZiwaixian().get(1);
		
		String result = "❤    早上好!这是今天的天气预报 \n"
					  + "❤    你的城市: %s\n"
					  + "❤    Pm值    : %s\n"
					  + "❤    当前温度: %s℃\n"
					  + "❤    风向    : %s\n"
					  + "❤    天气    : %s\n"
					  + "❤    温度    : %s\n"
					  + "❤    穿衣    : %s\n"
					  + "❤    我很贴心: %s\n"
					  + "❤    运动    : %s\n"
					  + "❤    紫外线 : %s\n";
		
		result = String.format(result, city, pm, temperature, direct, info, 
				wendu, chuanyi, tiexin, yundong, ziwaixian);
		return result;
	}
	
	private ArrayList<String> getResult1(Tianqi tianqi) {
		ArrayList<String> params = new ArrayList<String>();
		String pm = tianqi.getPm25().getPm25() + " " + tianqi.getPm25().getQuality();
		String temperature = tianqi.getRealtime().getWeather().getTemperature() + "℃";
		String direct = tianqi.getRealtime().getWind().getDirect();
		String info = tianqi.getRealtime().getWeather().getInfo();
		String wendu = "";
		List<WeatherBeanX> weather = tianqi.getWeather();
		for (WeatherBeanX w : weather) {
			if (w.getDate().equals(tianqi.getRealtime().getDate())) {
				wendu += w.getInfo().getNight().get(2);
				wendu += "℃ ~";
				wendu += w.getInfo().getDay().get(2) + "℃";
				break;
			}
		}
		params.add(pm);
		params.add(temperature);
		params.add(direct);
		params.add(info);
		params.add(wendu);
		return params;
	}
}

三、HttpUtils.java

package com.tianqi.autoSendTianqi.util;

import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpUtils {
	
	public static boolean doPost(String url, Object returnVo, String successValue, String successAttr) {
		String json = JSON.toJSONString(returnVo);
		boolean flag = false;
		for (int i = 0; i < 3; i++) {
			String result = httpPost(url, json);
			if (StringUtils.isNotBlank(result)) {
				JSONObject jo = JSONObject.parseObject(result);
				log.info("接口的URL===入参为:" + json + "第  " + i + "  次http请求==返回值:" + jo.getString(successValue));
				if (successAttr.equals(jo.getString(successValue))) {
					flag=true;
					break;
				}
			}
		}
		return flag;
	}

	public static String httpPost(String url, String json) {
		PostMethod method = new PostMethod(url);
		HttpClient httpClient = new HttpClient();
		try {
			HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(10000);
			managerParams.setSoTimeout(10000);
			RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8");
			method.setRequestEntity(entity);
			int statusCode = httpClient.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("HttpClient Error==[入参:" + json + "][statusCode = " + statusCode + "]");
				return "";
			}
			InputStream in = method.getResponseBodyAsStream();
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			char[] b = new char[4096];
			for (int n; (n = isr.read(b)) != -1;) {
				sb.append(new String(b, 0, n));
			}
			String returnStr = sb.toString();
			return returnStr;
		} catch (Exception e) {
			log.error("====接口的URL失败======" + json);
			e.getStackTrace();
		} finally {
			method.releaseConnection();
		}

		return "";
	}
	
	public static String httpGet(String url) {
		GetMethod method = new GetMethod(url);
		HttpClient httpClient = new HttpClient();
		try {
			HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(10000);
			managerParams.setSoTimeout(10000);
			int statusCode = httpClient.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("HttpClient Error==[statusCode = " + statusCode + "]");
				return "";
			}
			InputStream in = method.getResponseBodyAsStream();
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			char[] b = new char[4096];
			for (int n; (n = isr.read(b)) != -1;) {
				sb.append(new String(b, 0, n));
			}
			String returnStr = sb.toString();
			return returnStr;
		} catch (Exception e) {
			log.error("====接口的URL失败======");
			e.getStackTrace();
		} finally {
			method.releaseConnection();
		}

		return "";
	}
}

四、MailUtils.java

package com.tianqi.autoSendTianqi.util;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class MailUtils {
	@Value("${spring.mail.username}")
	private String from;

	@Autowired
	private JavaMailSender mailSender;

	/**
	 * 发送简单文本的邮件方法
	 * 
	 * @param to
	 * @param subject
	 * @param content
	 */
	public void sendSimpleMail(String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo(to);
		message.setFrom(from);
		message.setSubject(subject);
		message.setText(content);

		mailSender.send(message);
	}

	/**
	 * 发送HTML邮件的方法
	 * 
	 * @param to
	 * @param subjecr
	 * @param content
	 */
	public void sendHtmlMail(String to, String subjecr, String content) {
		MimeMessage message = mailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true);
			helper.setTo(to);
			helper.setFrom(from);
			helper.setSubject(subjecr);
			helper.setText(content, true);
			mailSender.send(message);
			log.info("发送静态邮件成功");
		} catch (MessagingException e) {
			log.error("发送静态邮件失败:", e);
		}

	}
}

五、Friend.java

package com.tianqi.autoSendTianqi.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Friend {
	private Integer id;
	private String name;
	private String email;
	private String phone;
}

六、FriendList.java

package com.tianqi.autoSendTianqi.vo;

import java.util.ArrayList;
import java.util.List;

/**
 * <p><b>FriendList Description:</b> 通知好友列表,邮件为空不发邮件,手机号为空不发短信</p>
 * @author douzi
 * <b>DATE</b> 2019年8月8日 下午9:55:52
 */
public class FriendList {
	public static List<Friend> getFriends() {
		List<Friend> friends = new ArrayList<Friend>();
		Friend f1 = new Friend(1, "志强", "XX@XX.com", "15000001010");
		Friend f2 = new Friend(2, "豆子", "XX@XX.com", "15000001011");
		Friend f3 = new Friend(2, "广敬", "XX@XX.com", "15000001012");
		Friend f4 = new Friend(2, "振杰", "XX@XX.com", "15000001013");
		Friend f5 = new Friend(3, "名威", "XX@XX.com", "15000001014");
		Friend f6 = new Friend(3, "清华", "XX@XX.com", "15000001015");
		friends.add(f1);
		friends.add(f2);
		friends.add(f3);
		friends.add(f4);
		friends.add(f5);
		friends.add(f6);
		return friends;
	}
}

七、Tianqi.java

由于类太长了,请自行通过 http://tq.360.cn/api/weatherquery/querys?app=tq360&code=101020100&t=201565159968966&c=201565260989066 返回的Json自动生成JavaBean,工具为:GsonFormater;

八、启动类

package com.tianqi.autoSendTianqi;

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

@SpringBootApplication
@EnableScheduling
public class AutoSendTianqiApplication {

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

}

九、返回结果:

邮件::::

手机短信::::

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

窦再兴

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值