Java發(fā)送天氣郵件

這是我第一次寫博客
文筆比較差拴疤,請見諒浩峡。

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

那就這樣了,
有錯誤請告訴我下
哪里寫的不好也告訴下
感謝看完

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末士复,一起剝皮案震驚了整個濱河市图谷,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌阱洪,老刑警劉巖便贵,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異冗荸,居然都是意外死亡嫉沽,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進店門俏竞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來绸硕,“玉大人,你說我怎么就攤上這事魂毁〔E澹” “怎么了?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵席楚,是天一觀的道長咬崔。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么垮斯? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任郎仆,我火速辦了婚禮,結(jié)果婚禮上兜蠕,老公的妹妹穿的比我還像新娘扰肌。我一直安慰自己,他們只是感情好熊杨,可當我...
    茶點故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布曙旭。 她就那樣靜靜地躺著,像睡著了一般晶府。 火紅的嫁衣襯著肌膚如雪桂躏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天川陆,我揣著相機與錄音剂习,去河邊找鬼。 笑死较沪,一個胖子當著我的面吹牛进倍,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播购对,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼陶因!你這毒婦竟也來了骡苞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤楷扬,失蹤者是張志新(化名)和其女友劉穎解幽,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體烘苹,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡躲株,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了镣衡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片霜定。...
    茶點故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖廊鸥,靈堂內(nèi)的尸體忽然破棺而出望浩,到底是詐尸還是另有隱情,我是刑警寧澤惰说,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布磨德,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏典挑。R本人自食惡果不足惜酥宴,卻給世界環(huán)境...
    茶點故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望您觉。 院中可真熱鬧拙寡,春花似錦、人聲如沸顾犹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽炫刷。三九已至擎宝,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間浑玛,已是汗流浹背绍申。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留顾彰,地道東北人极阅。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像涨享,于是被迫代替她去往敵國和親筋搏。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容