springboot实现调用第三方接口获取数据并存入数据库

简介

使用springboot框架,调取第三方接口的数据并存入mysql库

一、准备

1、准备一个第三方接口,我这里用的之前参考另一位大佬的文章使用的接口,并拿到appkey。链接在文末
在这里插入图片描述
在这里插入图片描述
2、根据返回参数,在mysql数据库新建对应表用于接收数据

CREATE TABLE `joke` (
  `id` varchar(100) DEFAULT NULL,
  `text` varchar(2000) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  `type` varchar(100) DEFAULT NULL,
  `ct` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3、idea直接新建一个springboot项目
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
这样方式比较快捷,直接生成的就会有启动类
eclipse参考:https://blog.csdn.net/qq_38320255/article/details/81327440

最终结构:
在这里插入图片描述
**controller层:**与前端进行交互
**service层:**业务逻辑
**domain层:**实体类
**dao层:**操作数据库

二、代码实现

1、controller层

package com.test.demo.controller;


import com.test.demo.service.JokeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * User: 59157
 * Date: 2020/12/2
 * Time: 14:51
 */
@Controller
public class JokeController {

    @Autowired
    JokeService jokeService;

    /**
     * 京东万象-笑话api
     */
    @RequestMapping("/getJoke")
    @ResponseBody
    public String jokeApi() throws Exception {
        //return "getjoke";
        jokeService.httpRequest();
        return "saved";
    }
}

2、service层

package com.test.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.test.demo.dao.JokeDao;
import com.test.demo.domain.Joke;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User: 59157
 * Date: 2020/12/2
 * Time: 14:53
 */
@Service
public class JokeService {

    private String jokeApiKey = "2e7xxxxxxxxxxxxxxxxxxxxxxc48";

    @Autowired
    JokeDao jokeDao;

    public void httpRequest() {
        //得到long类型当前时间
        long l = System.currentTimeMillis();
        //new日期对象
        Date date = new Date(l);
        //转换提日期输出格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = dateFormat.format(date);
        //调用的api的接口地址
        String apiPath = "https://way.jd.com/showapi/wbxh?time=" + time +
                "&page=1&maxResult=20&showapi_sign=bd0592992b4dxxxxxxxxxxxxx4db9f3&appkey=" + jokeApiKey;
        BufferedReader in = null;
        StringBuffer result = null;
        try {
            URL url = new URL(apiPath);
            //打开和url之间的连接
            HttpURLConnection connection = (HttpURLConnection) 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);
            }
            String result2 =  result.toString(); //返回json字符串
            //获取数据
            JSONObject jsonObject = JSON.parseObject(result2);
//            String code = jsonObject.getString("code");
//            System.out.println(apiPath);
//            System.out.println(code);
            JSONObject resultJsonObject = jsonObject.getJSONObject("result");
            JSONObject bodyJsonObject = resultJsonObject.getJSONObject("showapi_res_body");
            JSONArray jsonArray = bodyJsonObject.getJSONArray("contentlist");
            //遍历json集合,取出数据
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject2 = (JSONObject) jsonArray.get(i);
                //System.out.println(jsonObject2);
                Joke joke = new Joke();
                //jsonObject2.get("x_x").toString()中的“x_x”要和实际返回的json数据中的字段名一致,否则可能会出现找不到字段的错误提示
                joke.setId(jsonObject2.get("id").toString());
                joke.setText(jsonObject2.get("text").toString());
                joke.setTitle(jsonObject2.get("title").toString());
                joke.setType(jsonObject2.get("type").toString());
                joke.setCt(jsonObject2.get("ct").toString());
                //dao层保存数据存入数据库
                jokeDao.save(joke);
                }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

3、domain层

package com.test.demo.domain;


/**
 * User: 59157
 * Date: 2020/12/8
 * Time: 11:26
 */
public class Joke {
    private String ct;
    private String id;
    private String text;
    private String title;
    private String type;

    public String getCt() {
        return ct;
    }

    public void setCt(String ct) {
        this.ct = ct;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

4、dao层

package com.test.demo.dao;

import com.test.demo.domain.Joke;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * User: 59157
 * Date: 2020/12/8
 * Time: 14:52
 */
@Repository
public class JokeDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void save(Joke joke) {

        jdbcTemplate.update("insert into joke values(?,?,?,?,?)",
                joke.getId(),joke.getText(),joke.getTitle(),joke.getType(),joke.getCt());
    }

}

5、配置文件application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=xxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.tomcat.max-active=20
spring.datasource.dbcp2.max-idle=8
spring.datasource.dbcp2.min-idle=8
spring.datasource.dbcp2.initial-size=10

三、测试

1、启动
直接运行DemoApplication
在这里插入图片描述
2、直接localhost:8080/getJoke 调用成功
在这里插入图片描述
3、验证数据库
可以看到数据已经进来了
在这里插入图片描述

参考文章:
https://blog.csdn.net/qq_38320255/article/details/81327440
https://blog.csdn.net/myme95/article/details/89359677
https://blog.csdn.net/myme95/article/details/83106126

  • 32
    点赞
  • 250
    收藏
    觉得还不错? 一键收藏
  • 28
    评论
评论 28
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值