【Java】获取新浪股票接口,并且发到qq邮箱以及钉钉群

Java获取新浪股票接口并发送邮箱和钉钉机器人

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用

—利用java获取新浪股票,然后利用qq邮箱转发和钉钉机器人转发群消息。

提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、java获取新浪股票接口

示例:首先使用httpClient连接新浪的接口,然后获取。由于新浪接口年后更新了。如下所示:
https://hq.sinajs.cn/list=sh603399
获取新浪接口返回的值
Mian.java

出现以上这种情况我们代码请求协package cn.edu.zucc.iee.stock;
议要使用https,然后还有设置请求头,代码如下所示

package cn.edu.zucc.iee.stock;

import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        Demo demo = new Demo();
        Boolean isInRange = demo.isInRange();
        if(isInRange) demo.sendMessage();
    }
}

Demo.java

package cn.edu.zucc.iee.stock;

import cn.edu.zucc.iee.stock.Msg.DingTalk;
import cn.edu.zucc.iee.stock.Msg.Mail;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Demo {
    private String[] infoArray;
    private String name;
    private double price;
    private double price_pre;
    private String date;
    private String time;
    private Double stockRange;
    public Demo() throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://hq.sinajs.cn/list=sh603399"))
                                .setHeader("Referer", "https://finance.sina.com.cn")
                                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.body();
        String[] infoStrings = body.split("\"");
        infoArray = infoStrings[1].split(",");
        name = infoArray[0];
        price = Double.valueOf(infoArray[3]) ;
        price_pre = Double.valueOf(infoArray[2]) ;
        date = infoArray[30];
        time = infoArray[31];
        System.out.println(body);
        System.out.println(date);
    }
    public Boolean isInRange(){
        stockRange = price < price_pre ? price / price_pre - 1:price / price_pre;
        if(stockRange < 0.5 && stockRange > -0.5) return true;
        return false;
    }
    public void sendMessage(){
        String info = "\n截至 "
                        +date+" "
                        + time
                        +"\n股票名: "
                        +name
                        +"\n昨日收盘价: "
                        +price_pre
                        + "\n今日收盘价: "
                        + price
                        + "\n涨跌幅: "
                        + stockRange
                        +"\n该出手就出手吧,别逼逼";
        DingTalk dingTalk = new DingTalk();
        dingTalk.sendMessage(info);
        Mail mail = new Mail();
        mail.sendMessage(info);
    }
}

二、判断每天涨跌幅是不是小于5%,通过QQ邮箱转发信息。

qq邮箱要进行设置,通过短信发送设置,还要获取第三方登录验证码,这样就ok了。

代码如下(示例):

QQMail

package cn.edu.zucc.iee.stock.Msg;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class Mail implements IMsg{

    @Override
    public void sendMessage(String text) {
        // 收件人电子邮箱
        String to = "***********@qq.com,***********@qq.com"; //可以多个
        // 发件人电子邮箱
        String from = "***********@qq.com";

        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication("***********@qq.com", "********"); //发件人邮件用户名、授权码
            }
        });

        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.setRecipients(MimeMessage.RecipientType.TO,
                    InternetAddress.parse(to));

            // Set Subject: 头部头字段
            message.setSubject("股票警告!");

            // 设置消息体
            message.setText(text);

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....from runoob.com");
        }catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

三、判断每天涨跌幅是不是小于5%,通过钉钉机器人转发信息。

首先先设置一下钉钉机器人,可自行百度,拿到webhook,填入下面的*********。

钉钉机器人接口如下所示:
DingTalk.java

package cn.edu.zucc.iee.stock.Msg;

import java.util.HashMap;
import java.util.Map;

public class DingTalk implements IMsg{
    @Override
    public void sendMessage(String text) {
        // 钉钉的webhook
        String dingDingToken="***************************";
        // 请求的JSON数据,这里我用map在工具类里转成json格式
        Map<String,Object> json=new HashMap();
        Map<String,Object> texts=new HashMap();
        json.put("msgtype","text");
        texts.put("content","今日警告"+text);
        json.put("text",texts);
        // 发送post请求
        String response = SendHttps.sendPostByMap(dingDingToken, json);
        System.out.println("相应结果:"+response);
    }
}

SendHttps.java
这里的slf4就,要安装两个jar包,一个是slf4j-api,另外一个是slf4j-simple包,链接如下:
https://repo1.maven.org/maven2/org/slf4j/slf4j-simple/
https://repo1.maven.org/maven2/org/slf4j/slf4j-log4j12/

package cn.edu.zucc.iee.stock.Msg;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class SendHttps {
    private static Logger logger = LoggerFactory.getLogger(SendHttps.class);

    public static String sendPostByMap(String url, Map<String, Object> mapParam) {
        Map<String, String> headParam = new HashMap();
        headParam.put("Content-type", "application/json;charset=UTF-8");
        return sendPost(url, mapParam, headParam);
    }

    public static String sendPost(String url, Map<String, Object> param, Map<String, String> headParam) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Fiddler");

            if (headParam != null) {
                for (Entry<String, String> entry : headParam.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(JSON.toJSONString(param));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

效果如下所示:
在这里插入图片描述

总结

例如:以上就是今天要讲的内容,本文仅仅简单介绍了java对新浪股票接口的获取,然后发布qq邮箱以及钉钉机器人。
页面结构如下所示:
在这里插入图片描述

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值