李白
2026-05-29 c865989f10e5a1ae4bb78831a879210fcdca2f83
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
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.BipResVo;
import com.by4cloud.platformx.business.entity.invoice.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.net.URLDecoder;
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<String,Object> 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+"&timestamp="+timestamp+"&signature="+signature;
            String result = HttpUtil.get(url);
            if (result==null){
                continue;
            }
 
            try {
                BipResVo<BipTokenVo> tokenVo = JSON.parseObject(result,new TypeReference<BipResVo<BipTokenVo>>(){});
                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<String,Object> paramMap = new HashMap<>();
        paramMap.put("access_token","");
        paramMap.put("businessType","yonbip-fi-earapbill");
        paramMap.put("businessId","");
        paramMap.put("file",file);
        Map<String,Object> 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<String,Object> 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+"&timestamp="+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");
 
 
    }
}