张世豪
23 小时以前 03b0fb0ba2de86bcfff277778826547c0e37a93f
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
package jiekou;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * 取卡接口工具类 - 简化版本
 * 不使用外部JSON库,不包含重试逻辑
 */
public class TakeCardUtil {
 
    // 配置属性
    private static final Logger logger = LoggerFactory.getLogger(TakeCardUtil.class);
    private static final int CONNECT_TIMEOUT = 5000;
    private static final int READ_TIMEOUT = 10000;
 
    /**
     * 调用取卡接口
     * @param deviceId 设备ID
     * @param faceId 人脸ID
     * @param userId 用户ID
     * @return 响应结果JSON字符串
     */
    protected static String callTakeCardApi(
            String apiUrl,String apiKey,
            String deviceId, String faceId, String userId) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
 
        try {
            // 创建URL连接
            URL url = new URL(apiUrl);
            connection = (HttpURLConnection) url.openConnection();
 
            // 设置连接参数
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("apiKey", apiKey);
            connection.setConnectTimeout(CONNECT_TIMEOUT);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setDoOutput(true);
 
            // 构建请求体
            String requestBody = buildRequestBody(deviceId, faceId, userId);
            logger.info("取卡接口请求参数: {}", requestBody);
 
            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
 
            // 获取响应码
            int responseCode = connection.getResponseCode();
            logger.info("取卡接口响应码: {}", responseCode);
 
            // 读取响应内容
            StringBuilder response = new StringBuilder();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            } else {
                reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
            }
 
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
 
            String responseBody = response.toString();
            logger.info("取卡接口响应: {}", responseBody);
 
            return responseBody;
 
        } catch (Exception e) {
            logger.error("调用取卡接口发生异常", e);
            return buildErrorResponse("接口调用异常: " + e.getMessage());
        } finally {
            // 关闭资源
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("关闭BufferedReader失败", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
 
    /**
     * 构建请求体JSON
     * @param deviceId 设备ID
     * @param faceId 人脸ID
     * @param userId 用户ID
     * @return JSON格式的请求体
     */
    private static String buildRequestBody(String deviceId, String faceId, String userId) {
        return "{\"deviceId\":\"" + deviceId +
                "\",\"faceId\":\"" + faceId +
                "\",\"userId\":\"" + userId + "\"}";
    }
 
    /**
     * 构建错误响应
     * @param errorMsg 错误信息
     * @return JSON格式的错误响应
     */
    private static String buildErrorResponse(String errorMsg) {
        return "{\"code\":\"500\",\"status\":\"2\",\"msg\":\"" + errorMsg + "\"}";
    }
 
    /**
     * 判断响应是否允许取卡
     * @param responseJson 响应JSON字符串
     * @return true=允许取卡, false=不允许
     */
    public static boolean isTakeCardAllowed(String responseJson) {
        try {
            // 简单解析status字段
            if (responseJson != null && responseJson.contains("\"status\"")) {
                int statusIndex = responseJson.indexOf("\"status\"");
                if (statusIndex != -1) {
                    // 查找status值
                    int colonIndex = responseJson.indexOf(":", statusIndex);
                    int commaIndex = responseJson.indexOf(",", colonIndex);
                    int endIndex = responseJson.indexOf("}", colonIndex);
                    if (commaIndex == -1 || commaIndex > endIndex) {
                        commaIndex = endIndex;
                    }
 
                    if (colonIndex != -1 && commaIndex != -1) {
                        String statusValue = responseJson.substring(colonIndex + 1, commaIndex).trim();
                        statusValue = statusValue.replace("\"", "").replace("'", "");
                        return "1".equals(statusValue);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("解析响应状态失败", e);
        }
        return false;
    }
 
    /**
     * 从JSON字符串中提取指定字段的值
     * @param json JSON字符串
     * @param fieldName 字段名
     * @return 字段值,如果不存在则返回null
     */
    protected static String extractJsonField(String json, String fieldName) {
        try {
            if (json != null && json.contains("\"" + fieldName + "\"")) {
                int fieldIndex = json.indexOf("\"" + fieldName + "\"");
                if (fieldIndex != -1) {
                    // 查找字段值
                    int colonIndex = json.indexOf(":", fieldIndex);
                    int commaIndex = json.indexOf(",", colonIndex);
                    int endIndex = json.indexOf("}", colonIndex);
                    if (commaIndex == -1 || commaIndex > endIndex) {
                        commaIndex = endIndex;
                    }
 
                    if (colonIndex != -1 && commaIndex != -1) {
                        String fieldValue = json.substring(colonIndex + 1, commaIndex).trim();
                        // 去除引号
                        if (fieldValue.startsWith("\"") && fieldValue.endsWith("\"")) {
                            fieldValue = fieldValue.substring(1, fieldValue.length() - 1);
                        }
                        return fieldValue.isEmpty() ? null : fieldValue;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("提取字段 {} 失败", fieldName, e);
        }
        return null;
    }
}