SpringBoo后台GET请求接口数据,并保存到数据库

Posted 捡黄金的少年

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoo后台GET请求接口数据,并保存到数据库相关的知识,希望对你有一定的参考价值。

通过GET方式请求数据,并持久化到数据库,

逻辑如下

1、通过GET请求数据,并转化成字符串String格式

2、通过gson,将String转化为Json,再转化成对象

3、通过mybatisPlus的mapper中的insert方法持久化到数据库

1、接口数据展示

通过GET请求的数据接口到如下所示

{
    "data": [
        {
            "id": 31551,
            "card": "7182",
            "name": "7182",
            "sex": 1,
            "position": "",
            "workType": "检查人员",
            "x": "29.847349",
            "y": "92.081223",
            "time": "2021-09-01 17:43:18.0",
            "layer_id": 1003,
            "dm": "KB8-5061",
            "floor": null,
            "stationId": "426"
        }
    ],
    "status": "200",
    "msg": "请求接口成功"
}

2、GET方式请求数据接口,拿到字符串String

 public static final String ONLINE_PEOPLE_URL = "http://*******:8000/******";

public  void getOnlinePeople() {
        JsonObject object =null;
        try {
            URL url= new URL(ONLINE_PEOPLE_URL);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
             System.out.println("拿到GET结果"+sb.toString());
       
            

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
    }

3、将String转化为Json数组,用到gson

参考博主文章

(一)引入maven

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

(二)对字符串进行解析,sb.toString是GET拿到的字符串

            JsonParser parse =new JsonParser();
            object= (JsonObject) parse.parse(sb.toString());
            JsonElement data = object.get("data");
            JsonElement data2 = object.get("status");
            String asString = data2.getAsString();

4、解析的JSON,遍历转化为对象

JsonArray jsonArray = data.getAsJsonArray(); 将上面的JSonElement的对象转化成数组

 RegionPersonPointREQ userBean = gson.fromJson(user, RegionPersonPointREQ.class);通过遍历转化为对象,

JsonArray jsonArray = data.getAsJsonArray();

                Gson gson = new Gson();
                ArrayList<RegionPersonPointREQ> userBeanList = new ArrayList<>();
                for (JsonElement user : jsonArray) {
                    //使用GSON,直接转成Bean对象
                    RegionPersonPointREQ userBean = gson.fromJson(user, RegionPersonPointREQ.class);
                    userBeanList.add(userBean);

                    List<PersonPoint> personPoints = userBean.getPersonPoints();
                    for (PersonPoint re:personPoints
                    ) {
                        Integer id = re.getId();
                        re.setLineId(id);
                        re.setLinePreserve(1);
                        re.setId(null);
                        personPointMapper = (PersonPointMapper) SpringContextJobUtil.getBean("personPointMapper");
                        int insert = personPointMapper.insert(re);
                        if(insert>0){
                            System.out.println("添加成功");
                        }else {
                            System.out.println("添加失败");
                        }
                    }
                }

 RegionPersonPointREQ 如下所示

@Data
public class RegionPersonPointREQ {

    private  int id;
    private  String number;
    private  String name;
    private int sum;
    private List<PersonPoint> personPoints;

}

5、创建一个SpringContextJobUtil ,方便获得ApplicationContext中的所有bean,不然使用insert()方法插入会报错,

@Component
public class SpringContextJobUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    @SuppressWarnings("static-access" )
    public void setApplicationContext(ApplicationContext contex)
            throws BeansException {
        // TODO Auto-generated method stub
        this.context = contex;
    }
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }

    public static String getMessage(String key){
        return context.getMessage(key, null, Locale.getDefault());
    }
}

6、全部的代码如下   注释都比较齐全

  public static final String ONLINE_PEOPLE_URL = "http://***********:8000/*********";


    @Autowired
    PersonPointMapper personPointMapper;

    public  void getOnlinePeople() {
        JsonObject object =null;
        try {
            URL url= new URL(ONLINE_PEOPLE_URL);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println("拿到GET结果"+sb.toString());

            /**
             * 通过JsonParser将String转化为json
             *
             */
            JsonParser parse =new JsonParser();
            object= (JsonObject) parse.parse(sb.toString());
            JsonElement data = object.get("data");
            JsonElement data2 = object.get("status");
            String asString = data2.getAsString();
//            System.out.println("状态值"+asString);
            if(asString.equals("200")){

                JsonArray jsonArray = data.getAsJsonArray();

                Gson gson = new Gson();
                ArrayList<RegionPersonPointREQ> userBeanList = new ArrayList<>();
                for (JsonElement user : jsonArray) {
                    //使用GSON,直接转成Bean对象
                    RegionPersonPointREQ userBean = gson.fromJson(user, RegionPersonPointREQ.class);
                    userBeanList.add(userBean);

                    List<PersonPoint> personPoints = userBean.getPersonPoints();
                    for (PersonPoint re:personPoints
                    ) {
                        Integer id = re.getId();
                        re.setLineId(id);
                        re.setLinePreserve(1);
                        re.setId(null);
                        personPointMapper = (PersonPointMapper) SpringContextJobUtil.getBean("personPointMapper");
                        int insert = personPointMapper.insert(re);
                        if(insert>0){
                            System.out.println("添加成功");
                        }else {
                            System.out.println("添加失败");
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
    }

以上是关于SpringBoo后台GET请求接口数据,并保存到数据库的主要内容,如果未能解决你的问题,请参考以下文章

使用PHP开发一个简单的后台接口(响应移动端的get请求和post请求)

后台Post/Get 请求接口 方式

怎么通过ajax从后台获取json数据

react中向后台服务器发送一请求 后台接口返回的是byte[]类型的图片 我现在如何在前台界面中显示它?

浅谈前后端交互

php curl请求接口并获取数据