通过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("失败!");
        }
    }

POST带参数请求数据

如果下面找不到org.json包 则添加下面依赖

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

package com.example.duan_xin;
//
//
//import net.minidev.json.JSONObject;
//import org.json.JSONArray;
//import org.json.JSONException;
//
//import java.io.*;
//import java.net.HttpURLConnection;
//import java.net.URL;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * @program: duan_xin_demo
 * @ClassName test2
 * @description:
 * @author:蒋皓洁
 * @create: 2021-09-30 09:54
 * @Version 1.0
 **/
public class test2 {


    public static String getJsonData(JSONObject jsonParam, String urls) {
        StringBuffer sb = new StringBuffer();
        try {
            ;
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
            byte[] data = (jsonParam.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            conn.setRequestProperty("Content-Type", "application/json");
            // 开始连接请求
            conn.connect();
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            out.write((jsonParam.toString()).getBytes());
            out.flush();
            out.close();
            System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode() ){
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in1 = conn.getInputStream();
                try {
                    String readLine = new String();
                    BufferedReader responseReader = new BufferedReader(new InputStreamReader(in1, "UTF-8"));
                    while ((readLine = responseReader.readLine()) != null) {
                        sb.append(readLine).append("\n");
                    }
                    responseReader.close();
                    System.out.println(sb.toString());

                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            } else{
                System.out.println("error++");

            }

        } catch (Exception e) {

        }

        return sb.toString();

    }

    public static void main(String[] args) throws JSONException {
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("content", "当天上午9时许,天津南环铁路维修有限公司在南环铁路进行桥梁维修过程中发生坍塌事故。截至目前,事故共造成 7人死亡,5人受伤。施工方现场有关负责人已被公安机关控制。");

             String url = "http://localhost:7014/sys-user/test";
        String data = test2.getJsonData(jsonParam, url);
        //返回的是一个[{}]格式的字符串时:
//        JSONArray jsonArray = new JSONArray(data);
        //返回的是一个{}格式的字符串时:
//        JSONObject obj = new JSONObject(data);
//        System.out.println(obj);
    }




}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐