基于JAVA查询城市天气并实现定时推送

一:获取天气数据:(大致思路)

  • 使用第三方天气API,例如和风天气、OpenWeatherMap等,注册并获取API密钥。
  • 使用Java的网络请求库(如HttpClient)向API发送请求,获取城市的天气数据。
// 使用 HttpClient 发送 GET 请求
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("YOUR_WEATHER_API_URL"))
        .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

// 解析 JSON 数据
String responseBody = response.body();
// 使用 JSON 解析库,如 Jackson 或 Gson 解析 responseBody

二:推送天气信息:

  • 选择一种推送方式,如邮件、短信、App通知等。
  • 如果选择邮件推送,可以使用JavaMail API发送邮件。
  • 如果选择短信推送,可以使用短信服务提供商的API。
  • 如果选择App通知,可以使用Firebase Cloud Messaging(FCM)或其他推送服务。
// 以邮件为例,使用 JavaMail 发送邮件
Properties properties = new Properties();
properties.put("mail.smtp.host", "YOUR_MAIL_HOST");
properties.put("mail.smtp.port", "YOUR_MAIL_PORT");
properties.put("mail.smtp.auth", "true");

Session session = Session.getInstance(properties, new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("YOUR_EMAIL", "YOUR_PASSWORD");
    }
});

try {
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("YOUR_EMAIL"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("RECIPIENT_EMAIL"));
    message.setSubject("天气预报");
    message.setText("今日天气:" + weatherData); // 将天气信息作为邮件正文

    Transport.send(message);
} catch (MessagingException e) {
    e.printStackTrace();
}

如何实现早上定时推送?

要实现每天早上定时推送天气信息,您可以使用Java中的定时任务,例如ScheduledExecutorServiceTimer。以下是一个简单的示例代码,演示如何使用ScheduledExecutorService定时执行任务:

import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class WeatherApp {

    public static void main(String[] args) {
        // 创建定时任务执行器
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        // 每天早上7点执行任务
        int hour = 7;
        int minute = 0;
        int second = 0;

        // 计算距离下一次执行的时间间隔
        long initialDelay = calculateInitialDelay(hour, minute, second);

        // 执行定时任务
        scheduler.scheduleAtFixedRate(() -> {
            // 查询天气
            String weatherData = getWeatherData();

            // 推送天气信息
            sendWeatherNotification(weatherData);
        }, initialDelay, 24 * 60 * 60, TimeUnit.SECONDS);
    }

    private static long calculateInitialDelay(int targetHour, int targetMinute, int targetSecond) {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        long oneDayInMillis = 24 * 60 * 60 * 1000; // 一天的毫秒数

        // 计算目标时间点的毫秒数
        long targetTime = getTimeInMillis(targetHour, targetMinute, targetSecond);

        // 如果目标时间已过,则在下一天执行
        if (currentTime > targetTime) {
            targetTime += oneDayInMillis;
        }

        // 计算初始延迟时间
        return targetTime - currentTime;
    }

    private static long getTimeInMillis(int hour, int minute, int second) {
        return hour * 60 * 60 * 1000 + minute * 60 * 1000 + second * 1000;
    }

    private static String getWeatherData() {
        // 实现获取天气数据的逻辑
        // ...

        return "Today's weather: Sunny"; // 假设获取到的天气数据
    }

    private static void sendWeatherNotification(String weatherData) {
        // 实现推送天气信息的逻辑
        // ...
        System.out.println("Weather notification sent: " + weatherData);
    }
}

查询天气内容(详细步骤讲解)

前提:安装依赖:

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
 <groupId>com.squareup.okhttp3</groupId>
 <artifactId>okhttp</artifactId>
 <version>4.1.0</version>
</dependency>
  1. 首先利用JAVA来爬取指定天气网站。
public class GetPage{
public String getContent(String url){
OkHttpClient okHttpClient = new OkHttpClient();
    //定义一个请求配置URL
    Request request = new Request.Builder().url(url).build();
  
   Call call = okHttpClient.newCall(request)

    String result = null;
    result = call.execute().body().string();
}
    return result;
}

例如

image.png

package com.youkeda.test.http;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import java.io.IOException;




public class GetPage {

  /**
   * 根据输入的url,读取页面内容并返回
   */
  public String getContent(String url) throws IOException {
    OkHttpClient okHttpClient = new OkHttpClient();
    // 返回结果字符串
    Request request = new Request.Builder().url(url).build();

    Call call = okHttpClient.newCall(request);
    String result = null;
    result= call.execute().body().string();
    return result;
  }

  public static void main(String[] args) {
    GetPage getPage = new GetPage();
    String url ="https://www.pku.edu.cn//" +
            "\n";
    ;
    String content = null;
    try {
      content = getPage.getContent(url);
    } catch (IOException e) {
      e.printStackTrace();
    }

    System.out.println("API调用结果");
    System.out.println(url+content);
  }
}

有IP地址自动查询的API

https://ipservice.3g.163.com/ip
POST操作:

POST方法是一种用于向服务器提交数据的HTTP请求方法。在实际应用中,我们经常会用POST方法来提交用户的账号密码等敏感信息,以实现用户注册、登录、提交表单等操作。
HTTP/1.1协议规定的HTTP请求方法有OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT等几种。其中POST一般用来向服务端提交数据。
规范把HTTP请求分为三个部分:状态行、请求头、消息主体。协议规定POST提交的数据必须放在消息主体(entity-body)中,但协议并没有规定数据必须使用什么编码方式。所以说到POST提交数据方案,包含了Content-Type和消息主体编码方式两部分。
就是向界面提供账号密码进行登录的操作。

GET请求和post请求的区别:

image.png

查询手机信息的API

http://tcc.taobao.com/cc/json/mobile_tel_segment.htm

package com.youkeda.test.http;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;

public class FormPoster {

  public String postContent(String url, Map<String, String> formData) {
    // okHttpClient 实例
    OkHttpClient okHttpClient = new OkHttpClient();
    //post方式提交的数据
    Builder builer = new FormBody.Builder();
    // 放入表单数据
for (String key:formData.keySet()){
  builer.add(key,formData.get(key));
}
    // 构建 FormBody 对象
        FormBody formBody = builer.build();
    // 指定 post 方式提交FormBody
    Request request = new Request.Builder()
            .url(url)
            // addHeader("Referer", ...) 这个知识点在后面的章节中学到,目前不要纠结
            .addHeader("Referer", "https://www.taobao.com")
            .post(formBody)
            .build();

    // 使用client去请求
    Call call = okHttpClient.newCall(request);
    // 返回结果字符串
    String result = null;
    try {
      // 获得返回结果
      result = call.execute().body().string();
    } catch (IOException e) {
      // 抓取异常
      System.out.println("request " + url + " error . ");
      e.printStackTrace();
    }
    return result;
  }

  public static void main(String[] args) {
    String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
    Map<String, String> formData = new HashMap();
    formData.put("tel", "1840047xxxx");

    FormPoster poster = new FormPoster();
    String content = poster.postContent(url, formData);
  
    System.out.println("API调用结果");
    System.out.println(content);
  }
}

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值