第三方接口获取数据进行存入和更新数据库 |
您所在的位置:网站首页 › 从数据库获取数据存到本地的方法 › 第三方接口获取数据进行存入和更新数据库 |
需求介绍: 通过调用第三方接口每天定时进行对本地数据库进行新增的插入和修改的更新 第一步:准备 1.准备一个第三方接口用于测试,本文所用接口选择万维易源的一个免费接口,获取这种接口的方法网上有很多,不做赘述。
2.通过接口测试工具。测试接口可用性与返回参数(本处使用的是Apipost)
3.根据返回参数,在mysql数据库中建立对应的表进行数据的接收; 建表方式不做赘述;
二、代码实现 1.controller层 代码: package com.ndtl.yyky.common.yong; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @EnableScheduling @Controller public class YongController { @Autowired YongService yongService; @RequestMapping("") @ResponseBody @Scheduled(cron = "0 0 24 * * ?") //@Scheduled(cron = "0/15 * * * * ?") public String testApi(){ String api = "https://route.showapi.com/126-2?showapi_appid=XXXXX&showapi_sign=XXXXXXX"; yongService.httpRequest(api); return ""; } }
2.service层
源码: @Service @RestController public class YongService { @Autowired private YongDao yongDao; @Transactional public String httpRequest(String apiPath){ BufferedReader in = null; StringBuffer result = null; try { URL url =new URL(apiPath); //打开和url之间的连接 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); connection.connect(); result = new StringBuffer(); //读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result.append(line); } //return result.toString(); //返回json字符串 //获取接口数据 JSONObject jsonObject = JSON.parseObject(result.toString()); //检查接口是否正常通信 String code =jsonObject.getString("showapi_res_code"); //获取第一层数据 JSONObject jsonObject1 = jsonObject.getJSONObject("showapi_res_body"); //获取第二层数据 JSONObject jsonObject2 = jsonObject1.getJSONObject("pagebean"); //获取第三层数据 JSONArray jsonArray = jsonObject2.getJSONArray("contentlist"); //遍历json集合,取出数据 for(int i=0;i |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |