這是我第一次寫博客
文筆比較差拴疤,請見諒浩峡。
1.JSON
2.apache http
3.javax.mail
用到的包
天氣接口使用的是心知天氣
https://www.seniverse.com/
文檔還是很完善的巩那,申請了就可以用(免費的但是有次數(shù)要求)
大部分網(wǎng)絡(luò)代碼參考
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 = "發(fā)送方郵件";
// 此處參照 https://blog.csdn.net/qq422733429/article/details/51280020
private String authorization_code = "";
private String from = "接收方郵件";
private String subject = "主題";
private String text = "內(nèi)容";
public void sendEmail() {
Properties props = System.getProperties();
// 表示SMTP發(fā)送郵件,必須進行身份驗證
props.put("mail.smtp.auth", "true");
//此處填寫SMTP服務(wù)器
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);
// 構(gòu)建授權(quán)信息鹰晨,用于進行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 {
// 設(shè)置連接超時
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>風(fēng)向</th><th>風(fēng)向角度</th><th>風(fēng)速</th><th>風(fēng)力等級</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第一次用我只是把官網(wǎng)的實例復(fù)制過來。然后拼了一個表格加載數(shù)據(jù)模蜡。
3.JSONParser
先來講一下如何解析JSON漠趁,先來個簡單的。
{
"id": "C23NB62W20TF",
"name": "西雅圖",
"country": "US",
"timezone": "America/Los_Angeles",
"timezone_offset": "-07:00"
}
//轉(zhuǎn)成JSON對象
JSONObject jsonObject = JSONObject.fromObject(strJson);
//獲取JSON的Key
System.out.println(jsonObject.getString("id"));
結(jié)果:C23NB62W20TF
在來個難一點的JSON
{"results": [{
"location": {
"id": "C23NB62W20TF",
"name": "西雅圖",
"country": "US",
"timezone": "America/Los_Angeles",
"timezone_offset": "-07:00"
}
}]
}
//轉(zhuǎn)成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);
//在轉(zhuǎn)成JSON對象
jsonObject = JSONObject.fromObject(location_ja);
System.out.println("location:" + jsonObject.getString("location"));
//下面就不繼續(xù)了
結(jié)果:
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"}
下面展現(xiàn)我機智的時候到了忍疾,這種方法易錯率太高了4炒!B倍省甥绿!
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"));
結(jié)果:
{"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;
}
}
這個地方?jīng)]什么好說的了则披,能說的都說了
接下來關(guān)鍵的Main函數(shù)
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
那就這樣了,
有錯誤請告訴我下
哪里寫的不好也告訴下
感謝看完