接口对接json

发布于:2024-07-05 ⋅ 阅读:(19) ⋅ 点赞:(0)
public AjaxResult zhihuiya(@RequestBody ZlRecord zlRecord) {
        //查看用户或者部门有没有下载次数
        SysUser user = SecurityUtils.getLoginUser().getUser();
        ZlCount zlCount = newLabelMapper.selectUserCount(user.getUserId());
        if (ObjectUtils.isEmpty(zlCount)){
            ZlCount zlCount2 = newLabelMapper.selectDeptCount(user.getDeptId());
            if (ObjectUtils.isEmpty(zlCount2))
                throw new RuntimeException("该部门或用户没有下载次数");
        }
        //获取token
        String token="";
        String jobid="";
        String filePath="";
        String patentNumber="CN106561027B";
        String clientId="w6nf8ZI4AKA0oYgjJb";
        String clientSecret="Gy2geNN56TX1h79";
        String cacheObject = redisCache.getCacheObject("zha");
        if (StringUtils.isNotEmpty(cacheObject)){
            token = cacheObject;
        }else {
            String tokenhost = "https://"+clientId+":"+clientSecret+"@connect.ziya.com";
            String tokenpath = "/oauth/token";
            Map headers = new HashMap();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            Map requestbody = new HashMap();
            requestbody.put("grant_type", "client_credentials");
            try {
                HttpResponse response = HttpUtils.doPost(tokenhost, tokenpath, null, headers, null, requestbody);
                String result = EntityUtils.toString(response.getEntity());
                System.out.println(result);
                org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
                org.json.JSONObject data = jsonResponse.getJSONObject("data");
                if (data.has("token")&&StringUtils.isNotEmpty(data.getString("token"))){
                    token = "Bearer "+data.getString("token");
                    redisCache.setCacheObject("zhihuiya" , token, 25, TimeUnit.MINUTES);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException("获取token失败", HttpStatus.ERROR);
            }
        }


        //获取专利jobid
        String host = "https://connect.zya.com";
        String path = "/patent-valuation-data/patent-report/task/create";

        Map headers2 = new HashMap();
        headers2.put("Content-Type", "application/json");
        headers2.put("authorization", token);

        Map querys = new HashMap();
        querys.put("apikey", clientId);
        //JSONObject dataBody = (JSONObject) JSON.parse("{\"report_type\":\"pdf\",\"patent_number\":\"CN108977442B\"}");

        JSONObject dataBody = new JSONObject();
        dataBody.put("report_type", "pdf");
        dataBody.put("patent_number", zlRecord.getPatentNumber());
        try {
            HttpResponse response = HttpUtils.doPost(host, path, null, headers2, querys, dataBody.toJSONString());
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
            org.json.JSONObject data = jsonResponse.getJSONObject("data");
            jobid = data.getString("job_id");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("获取报告导出任务失败", HttpStatus.ERROR);
        }
        //获取导出链接
        String host3 = "https://connect.zhya.com";
        String path3 = "/patent-valuation-data/patent-report/job_id/status";

        Map headers3 = new HashMap();
        headers3.put("Content-Type", "application/json");
        headers3.put("authorization", token);

        Map querys3 = new HashMap();
        querys3.put("job_id", jobid);
        querys3.put("apikey", clientId);
        try {
            HttpResponse response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(result);
            org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
            org.json.JSONObject data = jsonResponse.getJSONObject("data");
            if (jsonResponse.has("error_code")&&jsonResponse.getInt("error_code")!=0){
                throw new ServiceException("下载报告失败"+jsonResponse.getInt("error_code"), HttpStatus.ERROR);
            }
            if (data.has("job_status")&&jsonResponse.getInt("error_code")==0){
                while (data.getInt("job_status")==1){
                    System.out.println("导出中");
                    Thread.sleep(5000); // 延迟1秒
                    response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
                    result = EntityUtils.toString(response.getEntity());
                    jsonResponse = new org.json.JSONObject(result);
                    data = jsonResponse.getJSONObject("data");
                }
                if (data.getInt("job_status")==2){
                    System.out.println("导出完成");
                    filePath = data.getString("download_url");
                }else {
                    throw new ServiceException("导出失败"+data.getInt("job_status")+"errorcode"+jsonResponse.getString("error_code"), HttpStatus.ERROR);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("导出报告失败", HttpStatus.ERROR);
        }
        String fileName1="";
        try {
            // 创建URL对象指向文件下载地址
            URL url = new URL(filePath);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 准备读取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String fileNameWithQuery = filePath.substring(filePath.lastIndexOf("/") + 1);
                int queryIndex = fileNameWithQuery.indexOf("?");
                String fileName = (queryIndex != -1) ? fileNameWithQuery.substring(0, queryIndex) : fileNameWithQuery;

                long currentTimeMillis = System.currentTimeMillis();

                 fileName1 = user.getUserId()+"_"+currentTimeMillis+"_"+fileName;
                // 指定本地保存的路径和文件名
                Path saveFilePath = Paths.get("/home/www/zlbg/", fileName1);

                // 创建文件输出流用于写入文件
                Files.copy(connection.getInputStream(), saveFilePath, StandardCopyOption.REPLACE_EXISTING);

                System.out.println("文件下载成功:" + saveFilePath.toAbsolutePath());
                System.out.println("/home/www/zlbg/"+ fileName1);
                zlRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                zlRecord.setFilePath("/home/www/zlbg/"+ fileName1);
                zlRecord.setUserId(user.getUserId());
                zlRecord.setDeptId(user.getDeptId());
                newLabelMapper.insertZlRecord(zlRecord);
                try {
                    if (ObjectUtils.isEmpty(zlCount)){
                        newLabelMapper.updateDeptCount(user.getDeptId());
                    }else {
                        newLabelMapper.updateUserCount(user.getUserId());
                    }

                } catch (Exception e) {
                    throw new ServiceException("文件下载次数超限", HttpStatus.ERROR);
                }
            } else {
                System.out.println("文件下载失败,响应码:" + responseCode);
                throw new ServiceException("文件下载失败", HttpStatus.ERROR);
            }

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("文件下载失败", HttpStatus.ERROR);
        }
        return AjaxResult.success("/home/www/zlbg/"+ fileName1);
    }

网站公告

今日签到

点亮在社区的每一天
去签到