package com.by4cloud.platformx.business.invoice.utils; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.by4cloud.platformx.business.entity.invoice.vo.BipResVo; import com.by4cloud.platformx.business.entity.invoice.vo.BipTokenVo; import com.by4cloud.platformx.business.utils.SignHelper; import lombok.RequiredArgsConstructor; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @Component @RequiredArgsConstructor public class BipHttpUtil { private static final Logger log = LoggerFactory.getLogger(BipHttpUtil.class); @Value("${bip.ip}") private String ip; @Value("${bip.filePath}") private String bipFilePath; @Value("${bip.appKey}") private String appKey; @Value("${bip.appSecret}") private String appSecret; private final RedisTemplate redisTemplate; public String getToken(){ String redisKey="BIP_TOKEN:"; // String appKey = "800b2805c5584f0abb8705acbe487dc5"; // String appSecret = "59ba72c62a6a27203d7e517787a738be89ba55cb"; redisKey+=appKey; if (redisTemplate.hasKey(redisKey)){ return (String) redisTemplate.opsForValue().get(redisKey); } for (int i=0;i<10;i++){ long timestamp = System.currentTimeMillis(); Map paramMap = new HashMap<>(); paramMap.put("appKey",appKey); paramMap.put("timestamp",timestamp); String signature = null; try { signature = SignHelper.sign(paramMap,appSecret); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { throw new RuntimeException(e); } String url = ip+BipApiEnum.获取TOKEN.getUrl()+"?appKey="+appKey+"×tamp="+timestamp+"&signature="+signature; String result = HttpUtil.get(url); if (result==null){ continue; } try { BipResVo tokenVo = JSON.parseObject(result,new TypeReference>(){}); if (tokenVo.getCode().equals("00000")){ redisTemplate.opsForValue().set(redisKey,tokenVo.getData().getAccess_token(),tokenVo.getData().getExpire()-10, TimeUnit.SECONDS); System.out.println("-------bipToken:"+tokenVo.getData().getAccess_token()); return tokenVo.getData().getAccess_token(); } }catch (Exception e){ throw new RuntimeException("bip访问接口异常,请检查网络是否正常"); } } return null; } public String post(BipApiEnum apiEnum,Object data){ log.warn("-------------bipPost-url:"+ip+apiEnum.getUrl()+"?access_token="+getToken()); log.warn("-------------bipPost-req:"+JSONUtil.toJsonStr(data)); try { String result = HttpRequest.post(ip+apiEnum.getUrl()+"?access_token="+getToken()) .body(JSONUtil.toJsonStr(data)) .timeout(10*3000) .execute().body(); log.warn("-------------bipPost-res:"+result); return result; }catch (Exception e){ e.printStackTrace(); log.error("-------------bipPost-res:请求失败"); throw new RuntimeException("BIP接口超时,请检查网络后重新尝试"); } } public String postUploadFile(String businessId,String fileLocalPath){ // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String param = "?access_token="+getToken()+"&businessType=yonbip-fi-earapbill&businessId="+businessId; // 创建HttpPost对象,并设置URL HttpPost httpPost = new HttpPost(ip+BipApiEnum.BIP文件上接口.getUrl()+param); // 创建MultipartEntityBuilder对象,并设置文件和其他参数 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("files", new File(bipFilePath+fileLocalPath), ContentType.MULTIPART_FORM_DATA, fileLocalPath); // 将MultipartEntityBuilder构建的实体对象设置到HttpPost对象中 HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 执行HttpPost请求,获取响应 HttpResponse response = null; String responseBody = null; try { response = httpClient.execute(httpPost); // 解析响应 HttpEntity responseEntity = response.getEntity(); responseBody= EntityUtils.toString(responseEntity); System.out.println(responseBody); // 关闭HttpClient httpClient.close(); } catch (IOException e) { throw new RuntimeException(e); } return responseBody; } public String postUploadFileUrl(String businessId,String fileLocalPath){ URL url = null; InputStream stream = null; String lastThreeChars = fileLocalPath.substring(fileLocalPath.length() - 3); String lowLast = lastThreeChars.toLowerCase(); if (lowLast.equals("png") || lowLast.equals("jpeg") || lowLast.equals("jpg")) { stream = pngToPdf(fileLocalPath, lowLast); } else { try { url = new URL(fileLocalPath); URLConnection connection = url.openConnection(); stream = connection.getInputStream(); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String param = "?access_token="+getToken()+"&businessType=yonbip-fi-earapbill&businessId="+businessId; // 创建HttpPost对象,并设置URL HttpPost httpPost = new HttpPost(ip+BipApiEnum.BIP文件上接口.getUrl()+param); // 创建MultipartEntityBuilder对象,并设置文件和其他参数 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 将MultipartEntityBuilder构建的实体对象设置到HttpPost对象中 builder.addBinaryBody("files", stream, ContentType.MULTIPART_FORM_DATA, "MX_"+System.currentTimeMillis()+".pdf"); HttpEntity entity = builder.build(); httpPost.setEntity(entity); // 执行HttpPost请求,获取响应 HttpResponse response = null; String responseBody = null; try { response = httpClient.execute(httpPost); // 解析响应 HttpEntity responseEntity = response.getEntity(); responseBody= EntityUtils.toString(responseEntity); System.out.println(responseBody); // 关闭HttpClient httpClient.close(); } catch (IOException e) { throw new RuntimeException(e); } return responseBody; } public InputStream pngToPdf(String filePath,String format){ //String bipFilePath = "/Users/kongdeqiang/Desktop/"; long l = System.currentTimeMillis(); InputStream stream = null; try { // 加载PNG图片 URL url1 = new URL(filePath); InputStream inputStream = url1.openStream(); OutputStream out = new FileOutputStream(bipFilePath+format+l+"."+format); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inputStream.read(buffer,0,8192)) !=-1){ out.write(buffer,0,bytesRead); } out.close(); inputStream.close(); File file = new File(bipFilePath+format+l+"."+format); BufferedImage image = ImageIO.read(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, format, baos); byte[] bytes = baos.toByteArray(); // 创建一个PDF文档 PDDocument document = new PDDocument(); PDPage page = new PDPage(new PDRectangle(image.getWidth(), image.getHeight())); document.addPage(page); // 将图片转换为PDF中的对象 PDImageXObject pdImage = PDImageXObject.createFromByteArray(document, bytes, format); PDPageContentStream contents = new PDPageContentStream(document, page); contents.drawImage(pdImage, 0, 0, image.getWidth(), image.getHeight()); contents.close(); // 保存PDF文档 document.save(bipFilePath+format+l+".pdf"); document.close(); stream = Files.newInputStream(Paths.get(bipFilePath+format+l+".pdf")); } catch (IOException e) { e.printStackTrace(); } return stream; } public String postDeleteFile(String businessId, String fid){ // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String param = "?access_token="+getToken()+"&businessType=yonbip-fi-earapbill&businessId="+businessId+"&fid="+fid; // 创建HttpPost对象,并设置URL HttpPost httpPost = new HttpPost(ip+BipApiEnum.BIP文件删除接口.getUrl()+param); // 执行HttpPost请求,获取响应 HttpResponse response = null; String responseBody = null; try { response = httpClient.execute(httpPost); // 解析响应 HttpEntity responseEntity = response.getEntity(); responseBody= EntityUtils.toString(responseEntity); System.out.println(responseBody); // 关闭HttpClient httpClient.close(); } catch (IOException e) { throw new RuntimeException(e); } return responseBody; } public static void main1(String[] args) { /* File file = new File("/Users/kongdeqiang/Desktop/1725590083564FFDXJS.pdf"); Map paramMap = new HashMap<>(); paramMap.put("access_token",""); paramMap.put("businessType","yonbip-fi-earapbill"); paramMap.put("businessId",""); paramMap.put("file",file); Map dataBody = new HashMap<>(); String result = HttpRequest.post("https://bip01.res.jzeg.cn"+BipApiEnum.BIP文件上接口.getUrl()) .form(paramMap) .timeout(10*1000) .execute().body(); System.out.println(result);*/ } public static void main(String[] args) throws Exception { //正式 // String appKey = "800b2805c5584f0abb8705acbe487dc5"; // String appSecret = "59ba72c62a6a27203d7e517787a738be89ba55cb"; //测试 // String appKey = "91d28a4b776a4ab992db225958cf2d93"; // String appSecret = "77abbe9a3bc647ccf4a2a08629a7a0316ffff830"; // for (int i=0;i<100;i++){ // long timestamp = System.currentTimeMillis(); // Map paramMap = new HashMap<>(); // paramMap.put("appKey",appKey); // paramMap.put("timestamp",timestamp); // String signature = SignHelper.sign(paramMap,appSecret); // System.out.println("signature:"+signature); // String url = "https://bip.res.jzeg.cn"+BipApiEnum.获取TOKEN.getUrl()+"?appKey="+appKey+"×tamp="+timestamp+"&signature="+signature; // System.out.println(url); // String result = HttpUtil.get(url); // System.out.println(result); // Thread.sleep(300); // } //InputStream pdf = BipHttpUtil.pngToPdf("/Users/kongdeqiang/Desktop/WechatIMG316.png", "png"); } }