RestTemplat从远程服务器上下载pdf-传递给第三方接口
-
从远程服务器上下载pdf
/** * 把服务器的pdf下载到本地 * @param resUrl 服务器地址 * @return */ public File getFilePdf(String resUrl) { URL url = null; InputStream is = null; OutputStream os = null; File file = null; try{ url = new URL(resUrl); //利用HttpURLConnection对象,我们可以从网络中获取网页数据. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.connect(); is = conn.getInputStream(); //得到网络返回的输入流 String pdfName = PathUtil.getTempPath() + File.separator + new Date().getTime() + ".pdf"; os = new FileOutputStream(pdfName); int len = 0; // 每次读取的有效字节个数 byte[] bytes = new byte[1024]; while((len = is.read(bytes)) != -1) { // 4. 使用字节输出流中的方法write, 把读取到的字节写入到目的地的文件中 os.write(bytes, 0, len); // 写入从bytes数组 0位置开始写入的长度为len } file = new File(pdfName); } catch (Exception e) { throw new BaseException("pdf文件下载失败!"); } finally { if (!ObjectUtils.isEmpty(is)) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (!ObjectUtils.isEmpty(os)) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; }
-
把pdf发送到第三方接口
/** * 把分析的pdf发送给 发改 * @return */ public Boolean uploadPdf(String projectId, String resUrl) { String sign = DigestUtils.md5DigestAsHex((projectId + RemoteInvocationConstant.APP_SECRET).getBytes()); String url = MessageFormat.format(RemoteInvocationConstant.UPLOAD_PDF, projectId, sign); File file = getFilePdf(resUrl); ResponseEntity<String> responseEntity = null; try{ //创建请求头 HttpHeaders httpHeaders = new HttpHeaders(); // 获取文件所在的绝对路径 FileSystemResource resource = new FileSystemResource(file); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); //参数 map.add("file", resource); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, httpHeaders); responseEntity = restTemplate.postForEntity(url, httpEntity, String.class); } catch (Exception e) { throw new BaseException("调用发改失败!"); } // 删除文件 file.delete(); if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) { return false; } String body = responseEntity.getBody(); if (StringUtils.isBlank(body)) { return false; } JSONObject jsonObject = JSON.parseObject(body); if (1 != (Integer)jsonObject.get("code")) { return false; } return true; }
-
入口
/** * 提交pdf到第三方平台 * * @param pid * @param projectId */ @Override public void submitPdfToFg(Integer pid, String projectId) { String resUrl = (String)redisTemplate.opsForValue().get(String.valueOf(pid)); if (StringUtils.isBlank(resUrl)) { throw new BaseException("pid:" + pid + "在redis中不存在, 请重新点击合规分析!"); } redisTemplate.delete(String.valueOf(pid)); Boolean isTrue = uploadPdf(projectId, resUrl); if (!isTrue) { throw new BaseException("pdf发送到第三方失败!"); } }
-
核心FileSystemResource 和 LinkedMultiValueMap