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

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

码云地址:

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

程序使用spring boot 2.0.8 结构为:

七夕送礼物-程序员也可以假浪漫_第1张图片

一、pom.xml



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.8.RELEASE
		 
	
	com.tianqi
	autoSendTianqi
	0.0.1-SNAPSHOT
	autoSendTianqi
	Demo project for Spring Boot

	
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
			com.alibaba
			fastjson
			1.2.47
		
		
			org.apache.commons
			commons-lang3
		
		
			commons-httpclient
			commons-httpclient
			3.1
		
		
		
			org.projectlombok
			lombok
			true
		

		
			org.springframework.boot
			spring-boot-starter-mail
		
		
		
			com.github.qcloudsms
			qcloudsms
			1.0.6
		
	

	
		${project.artifactId}
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


二、核心类: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 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 fs = FriendList.getFriends();
		
		sendMail(tianqi, fs);
	}
	
	/**
	 * 

Title: sendMail

*

Description:

* @author douzi * @param tianqi * @param fs */ private void sendMail(Tianqi tianqi, List 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); } }); } /** *

Title: sendPhone

*

Description:

* @author douzi * @param tianqi * @param fs */ private void sendPhone(Tianqi tianqi, List fs) { ArrayList 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); } /** *

Title: getResult

*

Description: 生成发送字符串

* @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 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 getResult1(Tianqi tianqi) { ArrayList params = new ArrayList(); 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 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;

/**
 * 

FriendList Description: 通知好友列表,邮件为空不发邮件,手机号为空不发短信

* @author douzi * DATE 2019年8月8日 下午9:55:52 */ public class FriendList { public static List getFriends() { List friends = new ArrayList(); Friend f1 = new Friend(1, "志强", "[email protected]", "15000001010"); Friend f2 = new Friend(2, "豆子", "[email protected]", "15000001011"); Friend f3 = new Friend(2, "广敬", "[email protected]", "15000001012"); Friend f4 = new Friend(2, "振杰", "[email protected]", "15000001013"); Friend f5 = new Friend(3, "名威", "[email protected]", "15000001014"); Friend f6 = new Friend(3, "清华", "[email protected]", "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);
	}

}

九、返回结果:

邮件::::

七夕送礼物-程序员也可以假浪漫_第2张图片

手机短信::::

七夕送礼物-程序员也可以假浪漫_第3张图片

你可能感兴趣的:(技术贴)