Java发送天气邮件
2018-04-21 本文已影响0人
天不错啊
这是我第一次写博客
文笔比较差,请见谅。
1.JSON
2.apache http
3.javax.mail
用到的包
天气接口使用的是心知天气
https://www.seniverse.com/
文档还是很完善的,申请了就可以用(免费的但是有次数要求)
大部分网络代码参考
http://hc.apache.org/httpcomponents-asyncclient-4.1.x/index.html
这篇博客写的很好,大部分邮件代码参照以下,用的QQ邮箱。
https://blog.csdn.net/qq422733429/article/details/51280020
项目截图如下
image
1.EmailManager类
public class EmailManager {
private String to = "发送方邮件";
// 此处参照 https://blog.csdn.net/qq422733429/article/details/51280020
private String authorization_code = "";
private String from = "接收方邮件";
private String subject = "主题";
private String text = "内容";
public void sendEmail() {
Properties props = System.getProperties();
// 表示SMTP发送邮件,必须进行身份验证
props.put("mail.smtp.auth", "true");
//此处填写SMTP服务器
props.put("mail.smtp.host", "smtp.qq.com");
props.put("mail.smtp.port", "587");
props.put("mail.user", to);
props.put("mail.password", authorization_code);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
System.out.println(subject);
message.setSubject(subject);
message.setSentDate(new java.util.Date());
message.setContent(text,"text/html;charset=UTF-8");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
2.AsyncClientPipelinedStreaming类
public class AsyncClientHttpExchangeFutureCallback {
public void HttpConnection(final HttpGet[] requests, String subject) throws IOException {
// 设置连接超时
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(3000)
.setConnectTimeout(3000).build();
//
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
try {
httpclient.start();
final CountDownLatch latch = new CountDownLatch(requests.length);
for (final HttpGet request : requests) {
httpclient.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(final HttpResponse response) {
latch.countDown();
try {
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
JSONParser parser = new JSONParser();
EmailManager manage = new EmailManager();
List<List<String>> listItems = parser.DailyParser(content);
StringBuffer sb = new StringBuffer();
sb.append("<style type=\"text/css\">");
sb.append("table.gridtable {font-family: verdana,arial,sans-serif;font-size:11px;color:#333333;border-width: 1px;border-color: #666666;border-collapse: collapse;}");
sb.append("table.gridtable th {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666;background-color: #dedede;}");
sb.append("table.gridtable td {border-width: 1px;padding: 8px;border-style: solid;border-color: #666666;background-color: #ffffff;}");
sb.append("</style>");
sb.append("<table class=\"gridtable\">");
sb.append("<tr><th>时间</th><th>最高温度</th><th>最低温度</th><th>白天天气</th><th>晚上天气</th><th>降水概率</th><th>风向</th><th>风向角度</th><th>风速</th><th>风力等级</th></tr>");
for (int i = 0; i < listItems.size(); i++) {
sb.append("<tr>");
for (int j = 0; j < listItems.get(i).size(); j++) {
sb.append("<td>" + listItems.get(i).get(j) + "</td>");
}
sb.append("</tr>");
}
System.out.println(sb.toString());
sb.append("</table>");
manage.setSubject(subject);
manage.setText(sb.toString());
manage.sendEmail();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(request.getRequestLine() + " cancelled");
}
});
}
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
httpclient.close();
}
}
}
HttpAsyncClients第一次用我只是把官网的实例复制过来。然后拼了一个表格加载数据。
3.JSONParser
先来讲一下如何解析JSON,先来个简单的。
{
"id": "C23NB62W20TF",
"name": "西雅图",
"country": "US",
"timezone": "America/Los_Angeles",
"timezone_offset": "-07:00"
}
//转成JSON对象
JSONObject jsonObject = JSONObject.fromObject(strJson);
//获取JSON的Key
System.out.println(jsonObject.getString("id"));
结果:C23NB62W20TF
在来个难一点的JSON
{"results": [{
"location": {
"id": "C23NB62W20TF",
"name": "西雅图",
"country": "US",
"timezone": "America/Los_Angeles",
"timezone_offset": "-07:00"
}
}]
}
//转成JSON对象
JSONObject jsonObject = JSONObject.fromObject(strJson);
//获取JSON的Key
String results = jsonObject.getString("results");
System.out.println("results:" + results);
//此处用JSONArray对象
JSONArray ja = JSONArray.fromObject(results);
//获取第一个元素
String location_ja = ja.getString(0);
System.out.println("location_ja:" + location_ja);
//在转成JSON对象
jsonObject = JSONObject.fromObject(location_ja);
System.out.println("location:" + jsonObject.getString("location"));
//下面就不继续了
结果:
results:[{"location":{"id":"C23NB62W20TF","name":"西雅图","country":"US","timezone":"America/Los_Angeles","timezone_offset":"-07:00"}}]
location_ja:{"location":{"id":"C23NB62W20TF","name":"西雅图","country":"US","timezone":"America/Los_Angeles","timezone_offset":"-07:00"}}
location:{"id":"C23NB62W20TF","name":"西雅图","country":"US","timezone":"America/Los_Angeles","timezone_offset":"-07:00"}
下面展现我机智的时候到了,这种方法易错率太高了!!!!
String strJson = "{\"results\":[{\"location\":{\"id\":\"C23NB62W20TF\",\"name\":\"西雅图\",\"country\":\"US\",\"timezone\":\"America/Los_Angeles\",\"timezone_offset\":\"-07:00\"}}]}";
// 字符串切片
strJson = strJson.substring(24, strJson.length() - 3);
System.out.println(strJson);
JSONObject jsonObject = JSONObject.fromObject(strJson);
System.out.println(jsonObject.getString("id"));
结果:
{"id":"C23NB62W20TF","name":"西雅图","country":"US","timezone":"America/Los_Angeles","timezone_offset":"-07:00"}
C23NB62W20TF
好啦 解析讲完了,下面看一下JSONParser类
public class JSONParser {
public List<List<String>> DailyParser(String strJson) {
List<List<String>> listItems = new ArrayList<>();
try {
strJson = strJson.substring(12, strJson.length() - 2);
JSONObject jsonObject = JSONObject.fromObject(strJson);
JSONArray items = JSONArray.fromObject(jsonObject.getString("daily"));
for (int item = 0; item < items.size(); item++) {
JSONArray array = JSONArray.fromObject(items.getJSONObject(item));
for (int i = 0; i < array.size(); i++) {
JSONObject temp = (JSONObject) array.get(i);
List<String> listItem = new ArrayList<>();
listItem.add(temp.getString("date"));
listItem.add(temp.getString("high"));
listItem.add(temp.getString("low"));
listItem.add(temp.getString("text_day"));
listItem.add(temp.getString("text_night"));
listItem.add(temp.getString("precip"));
listItem.add(temp.getString("wind_direction"));
listItem.add(temp.getString("wind_direction_degree"));
listItem.add(temp.getString("wind_speed"));
listItem.add(temp.getString("wind_scale"));
//listItem.put("code_day", temp.getString("code_day"));
//listItem.put("code_night", temp.getString("code_night"));
listItems.add(listItem);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return listItems;
}
}
这个地方没什么好说的了,能说的都说了
接下来关键的Main函数
public class Main {
public static void main(String[] args) throws IOException {
AsyncClientHttpExchangeFutureCallback streaming = new AsyncClientHttpExchangeFutureCallback();
streaming.HttpConnection(new HttpGet[]{new HttpGet("https://api.seniverse.com/v3/weather/daily.json?key=自己去申请&location=苏州&language=zh-Hans&unit=c&start=0&days=5")},"苏州天气");
}
}
也没啥好说的。
到了运行效果:
image.png
那就这样了,
有错误请告诉我下
哪里写的不好也告诉下
感谢看完