啊鑫
2025-08-20 65f2eac5d58297a6e9725da47d37b38c6a8af60a
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
package com.gs.xiaomi.service;
 
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gs.xiaomi.config.DataAcquisitionConfiguration;
import com.gs.xiaomi.dto.BCS101Request;
import com.gs.xiaomi.util.X5StringUtils;
import okhttp3.*;
import org.springframework.stereotype.Service;
 
import java.io.IOException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;
 
@Service
public class BCS101ApiService {
 
    private final OkHttpClient client;
    private final ObjectMapper objectMapper;
 
    public BCS101ApiService() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(90, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }
 
    /**
     * 获取BCS101数据
     *
     * @param request BCS101请求参数
     * @return API响应
     * @throws IOException 网络异常
     *                     <p>
     *                     HTTP访问需要Baisc Auth(该账户为条码集成专用账户,密码切勿输入错误!):
     *                     账户: RFCBCSXIAOBU
     *                     密码: L5X8!pdL
     *                     如何使用:
     *                     使用http 调用时需要根据账户密码增加http headers参数Authorization
     *                     对应的值为Basic bas64(账户:密码)
     *                     <p>
     *                     X5协议中使用的(国密算法)
     *                     对应appid和对应appkey请使用小米条码平台分配的对应的测试机信息:
     *                     APP ID:bcs_fty_177301
     *                     APP Key:IJBVGMJXG4ZTAMLSMFXGI33NONQWY5DG
     *                     <p>
     *                     HTTP HEADER参数:
     *                     Authorization  Basic XXXXX
     *                     同时请添加HTTP HEADER参数:
     *                     Content-Type  application/x-www-form-urlencoded
     *                     body选择raw,
     *                     数据格式为data=url编码(base64编码)的数据
     *                     </p>
     */
    public String getBCS101Data(BCS101Request request) throws IOException {
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
 
        // 构建form表单数据 - 按照注释要求:data=url编码(base64编码)的数据
        String formData = "data=" + urlEncodedData;
 
        // 构建Basic Auth - 使用专用条码集成账户
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 构建请求体 - Content-Type: application/x-www-form-urlencoded
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        // 构建请求 - 严格按照注释要求
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth)
                .build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                // 记录响应信息用于调试
                System.out.println("BCS101 API响应状态: " + response.code());
                System.out.println("BCS101 API响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 获取BCS101数据 - 带X5协议支持
     *
     * @param request  BCS101请求参数
     * @param enableX5 是否启用X5协议国密签名
     * @return API响应
     * @throws IOException 网络异常
     */
    public String getBCS101DataWithX5(BCS101Request request, boolean enableX5) throws IOException {
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
 
        // 构建form表单数据
        String formData = "data=" + urlEncodedData;
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 构建请求体
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded"));
 
        Request.Builder requestBuilder = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", "Basic " + auth);
 
        // 如果启用X5协议,添加国密签名
        if (enableX5) {
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String signature = generateX5Signature(
                    DataAcquisitionConfiguration.BCS_APP_ID,
                    DataAcquisitionConfiguration.BCS_APP_Key,
                    timestamp,
                    formData
            );
            requestBuilder.addHeader("X-App-Id", DataAcquisitionConfiguration.BCS_APP_ID)
                    .addHeader("X-Timestamp", timestamp)
                    .addHeader("X-Signature", signature);
        }
 
        Request httpRequest = requestBuilder.build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("BCS101 API响应状态: " + response.code());
                System.out.println("BCS101 API响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 生成X5协议签名 - 使用国密算法
     *
     * @param appId     APP ID
     * @param appKey    APP Key
     * @param timestamp 时间戳
     * @param data      请求数据
     * @return 签名字符串
     */
    private String generateX5Signature(String appId, String appKey, String timestamp, String data) {
        // X5协议国密算法签名: 尝试使用SM3,如果不支持则使用MD5
        String signString = appId + appKey + timestamp + data;
        try {
            // 尝试使用国密SM3算法
            return SmUtil.sm3(signString).toUpperCase();
        } catch (Exception e) {
            // 如果SM3不可用,fallback到MD5
            System.out.println("SM3算法不可用,使用MD5替代: " + e.getMessage());
            return DigestUtil.md5Hex(signString).toUpperCase();
        }
    }
 
    /**
     * 调试版本 - 详细输出请求信息来定位问题
     */
    public String getBCS101DataDebug(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API 调试信息 ===");
 
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
        System.out.println("1. 原始JSON数据: " + jsonData);
 
        // Base64编码
        String base64Data = X5StringUtils.encodeBase64(jsonData);
        System.out.println("2. Base64编码后: " + base64Data);
 
        // URL编码
        String urlEncodedData = URLEncoder.encode(base64Data, "UTF-8");
        System.out.println("3. URL编码后: " + urlEncodedData);
 
        // 构建form表单数据
        String formData = "data=" + urlEncodedData;
        System.out.println("4. Form数据: " + formData);
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
        System.out.println("5. Auth编码: Basic " + auth);
        System.out.println("6. 请求URL: " + DataAcquisitionConfiguration.BCS_101_URL);
 
        // 尝试不同的Content-Type
        RequestBody body = RequestBody.create(formData, MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"));
 
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
                .addHeader("Authorization", "Basic " + auth)
                .addHeader("Accept", "application/xml, text/xml, */*")
                .addHeader("User-Agent", "BCS101-Client/1.0")
                .addHeader("Connection", "close")
                .build();
 
        System.out.println("7. 发送请求...");
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("8. 响应状态码: " + response.code());
            System.out.println("9. 响应头: " + response.headers().toString());
 
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("10. 响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
 
    /**
     * 简化版本 - 尝试直接发送JSON数据
     */
    public String getBCS101DataSimple(BCS101Request request) throws IOException {
        System.out.println("=== BCS101 API 简化版本测试 ===");
 
        // 直接将请求对象转换为JSON字符串
        String jsonData = objectMapper.writeValueAsString(request);
        System.out.println("发送的JSON数据: " + jsonData);
 
        // 构建Basic Auth
        String credentials = DataAcquisitionConfiguration.BCS_USER_NAME + ":" + DataAcquisitionConfiguration.BCS_PWD;
        String auth = X5StringUtils.encodeBase64(credentials);
 
        // 尝试直接发送JSON数据(不经过Base64和URL编码)
        RequestBody body = RequestBody.create(jsonData, MediaType.parse("application/json; charset=utf-8"));
 
        Request httpRequest = new Request.Builder()
                .url(DataAcquisitionConfiguration.BCS_101_URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("Authorization", "Basic " + auth)
                .build();
 
        // 执行请求
        try (Response response = client.newCall(httpRequest).execute()) {
            System.out.println("简化版本响应状态: " + response.code());
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("简化版本响应内容: " + responseBody);
                return responseBody;
            }
            throw new IOException("Empty response body");
        }
    }
}