• 12.SpringBoot之RestTemplate的使用


    SpringBoot之RestTemplate的使用

    初识RestTemplate

    • RestTemplate是Spring框架提供用于调用Rest接口的一个应用,它简化了与http服务通信方式。RestTemplate统一Restfull调用的标准,封装HTTP链接,只要需提供URL及返回值类型即可完成调用。相比传统的HttpClient与Okhttp,
      RestTemplate是一种优雅,简洁调用RESTfull服务的方式。

    • RestTemplate默认依赖JDK提供Http连接的能力(HttpURLConnection),如果有需要的话也可以通过SetRequestFactory方法替换为如:Apache
      HttpComponents、Netty或OKHttp等其他HTTP库。

    本项目中所需数据获取平台:Tushare股票数据获取平台

    tushare数据接口讲解

    获取自己的token(令牌),是访问数据的关键
    01
    如何获取数据:
    02

    03
    04

    - 实时访问:需要积分的至少120起
     需要通过RestTemplate接口发送和接收信息。
    
    - 历史数据访问:不需要积分。
     直接下载成csv文件
    
    • 1
    • 2
    • 3
    • 4
    • 5

    05
    下载好的csv文件信息
    06

    实时数据访问

    获取数据字符串

    导入RestTemplate工具

    • 在Demo20230830Application中向spring注册RestTemplate工具
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.client.RestTemplate;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @SpringBootApplication
    @EnableSwagger2
    public class Demo20230830Application {
    
       public static void main(String[] args) {
           SpringApplication.run(Demo20230830Application.class, args);
       }
    
       /**
        * 向spring注册RestTemplate工具
        * @return
        */
       @Bean
       public RestTemplate getRestTemplate(){
           return new RestTemplate();
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 使用RestTemplate工具向tushare网站接口发送请求,从其接口中接收响应信息。
    • 在controller包下创建MyController2,在MyController2中输入
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @RestController
    @RequestMapping("/my2")
    public class MyController2 {
       //将RestTemplate工具导入到当前控制器中
       @Autowired
       RestTemplate restTemplate;
    
       @RequestMapping("/r1")
       public void r1(){
           //1、封装map参数
           HashMap<String, String> map = new HashMap<>();
           map.put("api_name","stock_company");
           map.put("token","你自己的token");
           //2、设置请求头信息
           HttpHeaders httpHeaders = new HttpHeaders();
           httpHeaders.setContentType(MediaType.APPLICATION_JSON);
           //3、封装头实体内容
           HttpEntity<Map> entity = new HttpEntity<>(map, httpHeaders);
           //4、传递信息
           String str = restTemplate.postForObject("http://api.tushare.pro", entity, String.class);
           System.out.println(str);
       }
    @RequestMapping("/r2")
    public void r2(){
       //1、封装map参数
       HashMap<String, String> map = new HashMap<>();
       map.put("api_name","stock_basic");
       map.put("token","你自己的token");
       //2、设置请求头信息
       HttpHeaders httpHeaders = new HttpHeaders();
       httpHeaders.setContentType(MediaType.APPLICATION_JSON);
       //3、封装头实体内容
       HttpEntity<Map> entity = new HttpEntity<>(map, httpHeaders);
       //4、传递信息
       String str = restTemplate.postForObject("http://api.tushare.pro", entity, String.class);
       System.out.println(str);
    }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    Fastjson转为json

    从tushare获取到的数据 复杂的json格式数据,如果我们自己进行String的数据解析,消耗大量时间。
    程序员会使用JSON工具,将字符串转为json,或将json转为其他数据类型。
    
    • 1
    • 2
    • 引入fastjson
      在pom.xml文件中引入,引入之后记得更新maven,不然不会生效
    
       com.alibaba
       fastjson
       1.2.17
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    07

    • 使用fastjson
    /**
    * fastjson的转换展示
    */
    @RequestMapping("/r3")
    public void r3(){
       //1、封装map参数
       HashMap<String, String> map = new HashMap<>();
       map.put("api_name","stock_basic");
       map.put("token","你自己的token");
       //2、设置请求头信息
       HttpHeaders httpHeaders = new HttpHeaders();
       httpHeaders.setContentType(MediaType.APPLICATION_JSON);
       //3、封装头实体内容
       HttpEntity<Map> entity = new HttpEntity<>(map, httpHeaders);
       //4、传递信息
       String str = restTemplate.postForObject("http://api.tushare.pro", entity, String.class);
       //5、JSON转换
       JSONObject jsonObject = JSONObject.parseObject(str);
       //获取请求id(测试用)
       String requestId = jsonObject.getString("request_id");
       //获取本次的所有数据
       JSONObject data = jsonObject.getJSONObject("data");
       //获取表头(数组)
       JSONArray fields = data.getJSONArray("fields");
       //fields.fori
       for (int i = 0; i < fields.size(); i++) {
           System.out.print(fields.get(i)+"\t\t");
       }
       System.out.println();
       //获取表格内部数据
       JSONArray items = data.getJSONArray("items");
       for (int i = 0; i < items.size(); i++) {
           JSONArray jsonArray = items.getJSONArray(i);
           //展示这一行的数据
           for (int j = 0; j < jsonArray.size(); j++) {
               System.out.print(jsonArray.get(j)+"\t\t");
           }
           System.out.println();
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    小结:
    获取的是{"k1":"v1","k2":"v2"} json格式,获取其中k2的值,v2
    JSONObject
    
    
    获取的是["a1","a2","a3"] json格式,获取其中a2
    JSONArray
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    历史数据访问

    导出csv文件

    在Tushare数据平台导出csv文件
    08
    导出的csv文件命名为stock_basic.csv

    OpenCSV

    完成Java程序和CSV之间的互通。

    • 导入OpenCSV环境:
    
       com.opencsv
       opencsv
       5.7.1
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    08

    • 使用OpenCSV进行解析
      在resources下新建csvdata包—在csvdata包下新建文件 stock_basic,把.txt后缀改为.csv
      09
      以下两种方式均可进行解析
    /**
    * openCSV
    */
    @RequestMapping("/r4")
    public void r4(){
       try(
               FileReader reader = new FileReader("D:\\\\project\\yanan_20230828\\demo_20230830\\src\\main\\resources\\csvdata\\stock_basic.csv"); //这里是刚新建stock_basic.csv文件的地址
               ) {
           CSVReader csvReader = new CSVReader(reader);
           List<String[]> list = csvReader.readAll();
           for (String[] arr : list) {
               //展示某一行的数据
               for (String s : arr) {
                   System.out.print(s+"\t\t");
               }
               System.out.println();
           }
       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } catch (CsvException e) {
           throw new RuntimeException(e);
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    /**
    * openCSV
    */
    @RequestMapping("/r5")
    public void r5() {
       File file;
       try {
           file = ResourceUtils.getFile("classpath:csvdata/stock_basic.csv");
       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       }
       try (
               FileReader reader = new FileReader(file);
       ) {
           CSVReader csvReader = new CSVReader(reader);
           List<String[]> list = csvReader.readAll();
           for (String[] arr : list) {
               //展示某一行的数据
               for (String s : arr) {
                   System.out.print(s + "\t\t");
               }
               System.out.println();
           }
       } catch (FileNotFoundException e) {
           throw new RuntimeException(e);
       } catch (IOException e) {
           throw new RuntimeException(e);
       } catch (CsvException e) {
           throw new RuntimeException(e);
       }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
  • 相关阅读:
    线性表顺序存储结构--(Java)
    大数据——Hadoop3.1.3安装与配置
    016——DHT11驱动开发(基于I.MX6uLL)
    【uniapp】六格验证码输入框实现
    FTC局部路径规划代码分析
    xml mysql 强制走区分大小写查询
    正则表达式
    Vue3中watchEffect侦听器的使用
    微服务框架 SpringCloud微服务架构 8 Gateway 网关 8.7 网关的cors 跨域配置
    Visual Studio部署C++矩阵库Armadillo的方法
  • 原文地址:https://blog.csdn.net/m0_58503202/article/details/133801470