• 【java调取第三方接口,获取数据并保存至数据库】


    java调取第三方接口,获取数据并保存至数据库

    如果需要添加token
    httpGet.addHeader(“Authorization”,token);
    httpGet.setHeader(“Authorization”,token);

    httpClient

    @Override
        public void doPost() {
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            String url = "http://xxx.xxx.xxx:8080/xxx/xxx/xxx";
       
            List<SaveProjectEntityDTO> list = new ArrayList<>();
            try {
                // 创建Http Post请求
                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
                
                //post传参数
                JSONObject param2= new JSONObject();
                param2.put("key","value");
                param2.put("key1", "value1");
                System.out.println(param2);
                httpPost.setEntity(new StringEntity(param2));
                // 执行http请求
                response = httpClient.execute(httpPost);
                //resultString 就是调取第三方接口后给的返回值
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
                //使用JSONObject.parseObject方法将字符串转化为JsonResult 实体类(JsonResult 类中的字段一定要对应返回值类型)
               JsonResult jsonResult = JSONObject.parseObject(resultString, JsonResult .class);
                //应为返回值中存在code,msg,success等信息,所以再使用JSONObject.parseArray方法将data中的数组取出来保存
                list = JSONObject.parseArray(jsonResult.getData(),SaveProjectEntityDTO.class);
                List<FwqProject> fwqProjects = new ArrayList<>();
                for (SaveProjectEntityDTO saveProjectEntityDTO : list){
                    FwqProject fwqProject = new FwqProject();
                    fwqProject.setzId(saveProjectEntityDTO.getId());
                    fwqProject.setName(saveProjectEntityDTO.getName());
                    fwqProject.setStatus(saveProjectEntityDTO.getStatus());
                    fwqProjects.add(fwqProject);
                }
                fwqProjectService.saveOrUpdateBatch(fwqProjects);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
    • 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

    HttpEntity

     String url="xxxxxx";
            HttpHeaders headers = new HttpHeaders();
            JSONObject param2= new JSONObject();
            param2.put("key1","value1");
            param2.put("key2", "value2");
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization","token");
            HttpEntity entity = new HttpEntity<>(param2,headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);
            System.out.println(response.getBody());
            JsonResult jsonResult = JSONObject.parseObject(response.getBody().toString(), JsonResult.class);
    
            if(jsonResult.getData() instanceof JSONObject){
                Objectt o= JSONObject.parseObject((jsonResult.getData()).toString(), Object.class);
                System.out.println(o);
            }else {
                List<Objectt > os = JSONObject.parseArray(( jsonResult.getData()).toString(), Objectt.class);
                System.out.println(tUsers);
    
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    JsonResult

    package com.example.swagger.entity.result;
    
    import com.example.swagger.entity.enums.ResultCodeEnum;
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    import lombok.Data;
    
    /**
     * 全局统一返回结果类
     */
    @Data
    @ApiModel(value = "全局统一返回结果")
    public class JsonResult<T> {
    
        @ApiModelProperty(value = "返回码")
        private Integer code;
    
        @ApiModelProperty(value = "返回消息")
        private String message;
    
        @ApiModelProperty(value = "返回数据")
        private T data;
    
        public JsonResult() {
        }
    
        protected static <T> JsonResult<T> build(T data) {
            JsonResult<T> jsonResult = new JsonResult<T>();
            if (data != null) {
                jsonResult.setData(data);
            }
            return jsonResult;
        }
    
        public static <T> JsonResult<T> build(T data, ResultCodeEnum resultCodeEnum) {
            JsonResult<T> jsonResult = build(data);
            jsonResult.setCode(resultCodeEnum.getCode());
            jsonResult.setMessage(resultCodeEnum.getMessage());
            return jsonResult;
        }
    
        public static <T> JsonResult<T> build(Integer code, String message) {
            JsonResult<T> jsonResult = build(null);
            jsonResult.setCode(code);
            jsonResult.setMessage(message);
            return jsonResult;
        }
    
        public static <T> JsonResult<T> ok() {
            return JsonResult.ok(null);
        }
    
        /**
         * 操作成功
         *
         * @param data
         * @param 
         * @return
         */
        public static <T> JsonResult<T> ok(T data) {
            JsonResult<T> jsonResult = build(data);
            return build(data, ResultCodeEnum.SUCCESS);
        }
    
        public static <T> JsonResult<T> fail() {
            return JsonResult.fail(null);
        }
    
        /**
         * 操作失败
         *
         * @param data
         * @param 
         * @return
         */
        public static <T> JsonResult<T> fail(T data) {
            JsonResult<T> jsonResult = build(data);
            return build(data, ResultCodeEnum.FAIL);
        }
    
        public JsonResult<T> message(String msg) {
            this.setMessage(msg);
            return this;
        }
    
        public JsonResult<T> code(Integer code) {
            this.setCode(code);
            return this;
        }
    
        public boolean isOk() {
            if (this.getCode().intValue() == ResultCodeEnum.SUCCESS.getCode().intValue()) {
                return true;
            }
            return false;
        }
    
    }
    
    • 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
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98

    JSONObject.parseObject,JSONObject.parseArray

    @Test
        public void test1(){
            String text = "{\"mode\":\"满减打折\",\"details\":[{\"order\":0,\"discountPercent\":10,\"min\":0,\"max\":100},{\"order\":1,\"discountPercent\":15,\"min\":100,\"max\":500}]}";
            JSONObject jsonObject = JSONObject.parseObject(text);
            String arrayStr = jsonObject.getString("details");
            List<Discount> list = JSONObject.parseArray(arrayStr,Discount.class);
            for(Discount discount:list){
                System.out.println(discount.toString()+"-------------");
            }
        }
    
        @Test
        public void test2(){
            String text = "{\"mode\":\"满减打折\",\"details\":[{\"order\":0,\"discountPercent\":10,\"min\":0,\"max\":100},{\"order\":1,\"discountPercent\":15,\"min\":100,\"max\":500}]}";
            JSONObject jsonObject = JSONObject.parseObject(text);
            JSONArray jsonArray = jsonObject.getJSONArray("details");
            for(int i = 0; i< jsonArray.size(); i++){
                // 写法一:
                // Discount discount = (Discount) jsonArray.get(i);
                // 写法二:
                JSONObject json = jsonArray.getJSONObject(i);
                Discount discount = json.toJavaObject(Discount.class);
                System.out.println(discount.toString()+"------------------");
            }
        }
    
    • 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

    fastjson判断一个json是jsonArray还是jsonObject几种方式

    
    ```java
       Object object = JSON.parse(dataStr);
            if (object instanceof JSONArray) {
                System.out.println("我是jsonArray");
            } else {
                System.out.println("我是jsonObject");
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    
    
    
    • 1
    • 2
  • 相关阅读:
    力扣第454题 四数相加 || c++哈希map使用
    2024/2/29 备战蓝桥杯 6-1 二分
    Linux 命令【8】:ssm
    理解JS的三座大山
    rust学习——方法 Method
    Intellij Idea屏蔽日志/过滤日志
    基于Springboot+Mybatis+mysql+vue技术交流博客论坛系统
    iOS 16 中 CoreData 托管对象发生变化但其衍生 (Derived) 属性在 SwiftUI 中不刷新的解决
    Linux学习第39天:Linux I2C 驱动实验(三):哥俩好
    Express 与 Koa 学习
  • 原文地址:https://blog.csdn.net/qq_45259214/article/details/133956672