中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java實現定時發送天氣預報

發布時間:2020-06-19 13:51:14 來源:億速云 閱讀:203 作者:元一 欄目:編程語言

技術棧

Spring Boot 2.3.1

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。

安裝Spring Boot 

可以在Spring倉庫中手動下載和安裝。一種更為簡便的方式是使用Groovy環境管理器(Groovy enVironment Manager,GVM),它會處理Boot版本的安裝和管理。Boot及其CLI可以通過GVM的命令行gvm install springboot進行安裝。在OS X上安裝Boot可以使用Homebrew包管理器。為了完成安裝,首先要使用brew tap pivotal/tap切換到Pivotal倉庫中,然后執行brew install springboot命令。

快速創建實例

前往 https://start.spring.io/ 如下所示
Java實現定時發送天氣預報
點擊GENERATE生產一個zip解壓導入idea即可

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 https://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.3.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.github.ekko</groupId>
    <artifactId>springboot-email</artifactId>
    <version>1.0.0</version>
    <name>springboot-email</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-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <!--阿里云主倉庫,代理了maven central和jcenter倉庫-->
        <repository>
            <id>aliyun</id>
            <name>aliyun</name>
            <url>https://maven.aliyun.com/repository/public</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <!--阿里云代理Spring 官方倉庫-->
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://maven.aliyun.com/repository/spring</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <!--阿里云代理Spring 插件倉庫-->
        <pluginRepository>
            <id>spring-plugin</id>
            <name>spring-plugin</name>
            <url>https://maven.aliyun.com/repository/spring-plugin</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories></project>

新建接收天氣api的實體

Weather.java

package com.github.ekko.springtools.model;import lombok.Data;import lombok.NoArgsConstructor;import java.util.List;@Data@NoArgsConstructorpublic class Weather {
    private String day;
    private String date;
    private String week;
    //天氣情況
    private String wea;
    private String weaImg;
    private String air;
    private String humidity;
    // 空氣質量 優
    private String airLevel;
    // 空氣質量描述:空氣很好,可以外出活動,呼吸新鮮空氣,擁抱大自然
    private String airTips;
    private String tem1;
    private String tem2;
    private String tem;

    private List<Whours> hours;}

Whours.java

package com.github.ekko.springtools.model;import lombok.Data;import lombok.NoArgsConstructor;@Data@NoArgsConstructorpublic class Whours {
    // 14日20時
    private String day;
    //中雨
    private String wea;
    //28℃ 實時溫度
    private String tem;
    //無持續風向
    private String win;
    // 風速 3-4級
    private String winSpeed;}

天氣接口

用的是https://www.tianqiapi.com/index
也沒給我推廣費,也作為我白嫖它這么久的回報吧
Java實現定時發送天氣預報

封裝的天氣api簡單演示

Java實現定時發送天氣預報

獲取天氣api與發送郵件的邏輯

新建EmailService.java接口

package com.github.ekko.springtools.service;import com.github.ekko.springtools.model.Weather;import java.util.List;public interface EmailService {
    boolean sendSimpleMessage();

    List<Weather> getWeather();}

實現EmailService接口

package com.github.ekko.springtools.service.impl;import cn.hutool.http.HttpRequest;import cn.hutool.http.HttpUtil;import com.alibaba.fastjson.JSON;import com.github.ekko.springtools.model.Weather;import com.github.ekko.springtools.service.EmailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.stereotype.Service;import javax.mail.internet.MimeMessage;import java.util.ArrayList;import java.util.List;import java.util.Optional;@Servicepublic class EmailServiceImpl implements EmailService {
    private final static String FROM_MAIL = "你的發送郵箱,和配置文件中相同";
    private final static String TO_MAIL = "接收人郵箱";
    private final static String APPID = "你申請的天氣api的appid,自行替換";
    private final static String APPSECRET = "你申請的天氣api的APPSECRET,自行替換";

    public JavaMailSender emailSender;

    @Autowired
    public void setEmailSender(JavaMailSender emailSender) {
        this.emailSender = emailSender;
    }

    @Override
    public boolean sendSimpleMessage() {
        try {
            MimeMessage message = emailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setTo(TO_MAIL);
            mimeMessageHelper.setFrom(FROM_MAIL);
            mimeMessageHelper.setSubject("今日份天氣到了~~");
            mimeMessageHelper.setText(buildHtml(getWeather().get(0)), true);
            emailSender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public List<Weather> getWeather() {
        HttpRequest httpRequest = HttpUtil.createGet("https://www.tianqiapi.com/api?version=v1&" + "appid=" + APPID + "&appsecret=" + APPSECRET + "&cityid=101020100");
        String res = httpRequest.execute().body();
        Object data = JSON.parseObject(res).get("data");

        return JSON.parseArray(JSON.toJSONString(data), Weather.class);
    }

    private String buildHtml(Weather weather) {
        StringBuffer html = new StringBuffer("");
        html.append("<!DOCTYPE html>\n" +
                "<html>\n" +
                "<head>\n" +
                "<meta charset=\"utf-8\">\n" +
                "<title>文檔標題</title>\n" +
                "</head><body>");
        if (weather.getWea().contains("雨")) {
            html.append("<h2>今日有雨,狗子請帶傘!</h2>");
        }
        html.append("<hr/><h4>今日天氣如下</h4><table><tr><th>時間</th><th>天氣</th><th>溫度</th></tr>");
        Optional.ofNullable(weather.getHours())
                .orElse(new ArrayList<>())
                .forEach(whours -> {
                    html.append("<tr><td>")
                            .append(whours.getDay())
                            .append("</td><td>")
                            .append(whours.getWea())
                            .append("</td><td>")
                            .append(whours.getTem())
                            .append("</td></tr>");
                });

        html.append("</table></body>" +
                "</html>");
        return html.toString();
    }}

代碼中的APPIDAPPSECRET
Java實現定時發送天氣預報

設置發送賬號信息

這里以騰訊郵箱為例子 ,先獲取發送郵件的授權碼
Java實現定時發送天氣預報
查詢其郵箱的SMTP地址 ,鏈接 ,可以看到

使用SSL的通用配置如下:
接收郵件服務器:pop.qq.com,使用SSL,端口號995
發送郵件服務器:smtp.qq.com,使用SSL,端口號465或587
賬戶名:您的QQ郵箱賬戶名(如果您是VIP帳號或Foxmail帳號,賬戶名需要填寫完整的郵件地址)
密碼:您的QQ郵箱密碼
電子郵件地址:您的QQ郵箱的完整郵件地址

配置appliction.properties

server.port=9090
server.servlet.context-path=/mail
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=你的郵箱地址
spring.mail.password=剛剛獲取的授權碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.starttls.enable=true

控制層

聲明 @EnableScheduling定時任務
給指定方法設置時間表達式@Scheduled(cron = "0 0 8 * * ? ")

package com.github.ekko.springtools.controller;import com.github.ekko.springtools.model.Weather;import com.github.ekko.springtools.service.EmailService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController@EnableSchedulingpublic class MailController {

    private EmailService emailService;

    @Autowired
    public void setEmailService(EmailService emailService) {
        this.emailService = emailService;
    }

    @GetMapping("/send")
    @Scheduled(cron = "0 0 23 * * ? ")
    public boolean sendEmail() {
        return emailService.sendSimpleMessage();
    }

    @GetMapping("get-weather")
    public List<Weather> getWeather() {
        return emailService.getWeather();
    }}

啟動類

直接啟動SpringbootEmailApplication即可

package com.github.ekko.springtools;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringbootEmailApplication {

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

效果

Java實現定時發送天氣預報

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

普兰县| 元氏县| 永州市| 特克斯县| 绥阳县| 平阴县| 嘉善县| 芷江| 青田县| 正安县| 南华县| 隆尧县| 安福县| 琼结县| 龙里县| 开江县| 潮州市| 钦州市| 通江县| 沂水县| 杭州市| 阿拉善左旗| 治多县| 轮台县| 富民县| 孝昌县| 三明市| 崇礼县| 洛隆县| 汝阳县| 铜川市| 旌德县| 江安县| 涿鹿县| 淮北市| 边坝县| 康保县| 涟源市| 定边县| 本溪市| 嘉善县|