ApiClient.java 19.7 KB
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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
package cn.com.glsx.schedulerjob.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.var;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import java.io.Closeable;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
/**
 * API 客户端 - 保持与原代码相同的三种模式设计
 *
 * 模式一:仅生成签名头(signGet / signPost)
 * 模式二:签名后直接请求(requestWithSignGet / requestWithSignPost)
 * 模式三:Token 自动管理(get / post)
 11 / 32
 第三方接口接入文档 | API Integration Guide */
public class ApiClient implements Closeable {
    private static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper();
    private static final String DEFAULT_TOKEN_API = "/v1/auth/getToken";
    private static final Duration DEFAULT_TOKEN_REFRESH_BEFORE = Duration.ofMinutes(5);
    private final String systemKey;
    private final String privateKey;
    private final String baseUrl;
    private final String tokenApi;
    private final CloseableHttpClient httpClient;
    private final ObjectMapper objectMapper;
    private final Duration tokenRefreshThreshold;
    private final AtomicReference<TokenHolder> tokenHolder = new AtomicReference<>();
    private final Lock tokenRefreshLock = new ReentrantLock();
    private final boolean autoCloseHttpClient;
    // ==================== 构造函数 ====================
    public ApiClient(String systemKey, String privateKey, String baseUrl) {
        this(builder().systemKey(systemKey).privateKey(privateKey).baseUrl(baseUrl));
    }
    public ApiClient(String systemKey, String privateKey, String baseUrl, String
            tokenApi) {
        this(builder()
                .systemKey(systemKey)
                .privateKey(privateKey)
                .baseUrl(baseUrl)
                .tokenApi(tokenApi));
    }
    private ApiClient(Builder builder) {
        this.systemKey = Objects.requireNonNull(builder.systemKey, "systemKey 不能为空");
        this.privateKey = Objects.requireNonNull(builder.privateKey, "privateKey 不能为空 ");
        this.baseUrl = normalizeUrl(builder.baseUrl);
        this.tokenApi = builder.tokenApi != null ? builder.tokenApi : DEFAULT_TOKEN_API;
        this.objectMapper = builder.objectMapper != null ? builder.objectMapper :
                DEFAULT_MAPPER;
        this.tokenRefreshThreshold = builder.tokenRefreshThreshold != null ?
                builder.tokenRefreshThreshold : DEFAULT_TOKEN_REFRESH_BEFORE;
        if (builder.httpClient != null) {
             this.httpClient = builder.httpClient;
            this.autoCloseHttpClient = false;
        } else {
            this.httpClient = createDefaultHttpClient();
            this.autoCloseHttpClient = true;
        }
    }
    public static Builder builder() {
        return new Builder();
    }
// ==================== 模式一:仅生成签名头 ====================
    /**
     * 生成 GET 请求签名头(无 body)
     */
    public Map<String, String> signGet(String api) throws ApiException {
        return signGet(api, null);
    }
    public Map<String, String> signGet(String api, Map<String, String> queryParams)
            throws ApiException {
        String apiIdentifier = buildApiIdentifier(api, queryParams);
        return doSign("GET", apiIdentifier, "");
    }
    /**
     * 生成 POST 请求签名头(有 body)
     */
    public Map<String, String> signPost(String api, String body) throws ApiException {
        return signPost(api, null, body);
    }
    public Map<String, String> signPost(String api, Map<String, String> queryParams,
                                        String body) throws ApiException {
        String apiIdentifier = buildApiIdentifier(api, queryParams);
        return doSign("POST", apiIdentifier, body != null ? body : "");
    }
// ==================== 模式二:签名后直接请求 ====================
    /**
     13 / 32
     第三方接口接入文档 | API Integration Guide * GET 请求:签名并执行(无 body)
     */
    public String requestWithSignGet(String api) throws ApiException {
        return requestWithSignGet(api, null);
    }
    public String requestWithSignGet(String api, Map<String, String> queryParams) throws
            ApiException {
        Map<String, String> headers = signGet(api, queryParams);
        String fullUrl = buildFullUrl(api, queryParams);
        HttpGet httpGet = new HttpGet(fullUrl);
        return executeRequest(httpGet, headers);
    }
    /**
     * POST 请求:签名并执行(有 body)
     */
    public String requestWithSignPost(String api, String body) throws ApiException {
        return requestWithSignPost(api, null, body);
    }
    public String requestWithSignPost(String api, Map<String, String> queryParams,
                                      String body) throws ApiException {
        Map<String, String> headers = signPost(api, queryParams, body);
        String fullUrl = buildFullUrl(api, queryParams);
        HttpPost httpPost = new HttpPost(fullUrl);
        return executeRequest(httpPost, body, headers);
    }
// ==================== 模式三:Token 模式(自动管理 Token)====================
    /**
     * Token 模式 - GET(无 body)
     */
    public String get(String api) throws ApiException {
        return requestWithToken(api, null, null);
    }
    public String get(String api, Map<String, String> queryParams) throws ApiException {
        return requestWithToken(api, queryParams, null);
    }
     /**
     * Token 模式 - POST(有 body)
     */
    public String post(String api, String body) throws ApiException {
        return requestWithToken(api, null, body);
    }
    /**
     * Token 模式 - 通用方法
     * GET 时 body 传 null,POST 时 body 传 JSON 字符串
     */
    public String requestWithToken(String api, Map<String, String> queryParams, String
            body) throws ApiException {
        String token = ensureValidToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + token);
        headers.put("Content-Type", "application/json");
        String fullUrl = buildFullUrl(api, queryParams);
        HttpUriRequest request;
        if (body == null || body.isEmpty()) {
            request = new HttpGet(fullUrl);
        } else {
            HttpPost post = new HttpPost(fullUrl);
            post.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
            request = post;
        }
        try {
            return executeRequest(request, headers);
        } catch (UnauthorizedException e) {
// Token 过期,刷新后重试一次
            refreshToken();
            headers.put("Authorization", "Bearer " + ensureValidToken());
            return executeRequest(request, headers);
        }
    }
    /**
     * 强制刷新 Token(线程安全)
     15 / 32
     第三方接口接入文档 | API Integration Guide */
    public void refreshToken() throws ApiException {
        tokenRefreshLock.lock();
        try {
            tokenHolder.set(null);
            ensureValidToken();
        } finally {
            tokenRefreshLock.unlock();
        }
    }
    // ==================== 内部实现 ====================
    private Map<String, String> doSign(String method, String apiIdentifier, String body)
            throws ApiException {
        try {
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String nonce = generateNonce();
            String bodyHash = sha256Hex(body);
            String signStr = String.join("|", method, apiIdentifier, bodyHash, timestamp,
                    nonce, systemKey);
            String signature = ECDSAUtil.sign(signStr, privateKey);
            Map<String, String> headers = new LinkedHashMap<>();
            headers.put("X-Key", systemKey);
            headers.put("X-Timestamp", timestamp);
            headers.put("X-Nonce", nonce);
            headers.put("X-Signature", signature);
            headers.put("X-Api", apiIdentifier);
            headers.put("Content-Type", "application/json");
            return headers;
        } catch (Exception e) {
            throw new SignatureException("签名生成失败", e);
        }
    }
    private String ensureValidToken() throws ApiException {
        TokenHolder current = tokenHolder.get();
// 快速路径:Token 有效
        if (current != null && !current.isExpiringSoon(tokenRefreshThreshold)) {
            return current.token;
        }
        // 慢速路径:需要获取新 Token(带锁)
        tokenRefreshLock.lock();
        try {
// 双重检查
            current = tokenHolder.get();
            if (current != null && !current.isExpiringSoon(tokenRefreshThreshold)) {
                return current.token;
            }
            return fetchNewTokenInternal();
        } finally {
            tokenRefreshLock.unlock();
        }
    }
    private String fetchNewTokenInternal() throws ApiException {
        try {
            Map<String, String> headers = signPost(tokenApi, "");
            String url = baseUrl + tokenApi;
            HttpPost httpPost = new HttpPost(url);
            headers.forEach(httpPost::addHeader);
            httpPost.setEntity(new StringEntity("", StandardCharsets.UTF_8));
            String result = executeRequest(httpPost, Collections.emptyMap());
            JsonNode json = objectMapper.readTree(result);
            int code = json.path("code").asInt(-1);
            if (code != 200) {
                String msg = json.path("msg").asText("未知错误");
                throw new TokenException("获取 Token 失败: " + msg);
            }
            JsonNode data = json.path("data");
            String accessToken = data.path("access_token").asText();
            long expiresIn = data.path("expires_in").asLong(3600);
            if (accessToken == null || accessToken.isEmpty()) {
                throw new TokenException("Token 响应缺少 access_token");
            }
            tokenHolder.set(new TokenHolder(accessToken, expiresIn));
            return accessToken;
        } catch (IOException e) {
            throw new TokenException("获取 Token 网络错误", e);
        }
    }
    // ==================== HTTP 执行与工具方法 ====================
    private String executeRequest(HttpUriRequest request, Map<String, String> headers)
            throws ApiException {
        return executeRequest(request, null, headers);
    }
    private String executeRequest(HttpUriRequest request, String body, Map<String,
            String> headers) throws ApiException {
        headers.forEach(request::addHeader);
        if (body != null && request instanceof HttpPost) {
            ((HttpPost) request).setEntity(new StringEntity(body,
                    StandardCharsets.UTF_8));
        }
        try {
            var response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity(),
                    StandardCharsets.UTF_8);
            if (statusCode == 401) {
                throw new UnauthorizedException(result);
            }
            if (statusCode < 200 || statusCode >= 300) {
                throw new HttpException(statusCode, "HTTP " + statusCode + ": " +
                        result);
            }
            return result;
        } catch (IOException e) {
            throw new ApiException("请求执行失败: " + e.getMessage(), e);
        }
    }

    private String buildApiIdentifier(String api, Map<String, String> queryParams) {
        String normalizedApi = api.startsWith("/") ? api : "/" + api;
        if (queryParams == null || queryParams.isEmpty()) {
            return normalizedApi;
        }
        String queryString = queryParams.entrySet().stream()
                .filter(e -> e.getKey() != null)
                .sorted(Map.Entry.comparingByKey())
                .map(e -> {
                    String key = e.getKey();
                    String value = e.getValue() != null ? e.getValue() : "";
                    return key + "=" + urlEncode(value);
                })
                .collect(Collectors.joining("&"));
        return normalizedApi + "?" + queryString;
    }
    private String buildFullUrl(String api, Map<String, String> queryParams) {
        String url = api.startsWith("http") ? api : baseUrl + api;
        if (queryParams == null || queryParams.isEmpty()) {
            return url;
        }
        String queryString = queryParams.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getKey() + "=" + urlEncode(e.getValue()))
                .collect(Collectors.joining("&"));
        String separator = url.contains("?") ? "&" : "?";
        return url + separator + queryString;
    }
    @SneakyThrows
    private static String urlEncode(String value) {
        if (value == null) return "";
        return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replace("+",
                "%20");
    }
    private static String sha256Hex(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 不可用", e);
        }
    }
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    private static String generateNonce() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
    private static String normalizeUrl(String url) {
        if (url == null) throw new IllegalArgumentException("baseUrl 不能为空");
        return url.endsWith("/") ? url.substring(0, url.length() - 1) : url;
    }
    private static CloseableHttpClient createDefaultHttpClient() {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(200);
        cm.setDefaultMaxPerRoute(50);
        cm.closeIdleConnections(30, TimeUnit.SECONDS);
        return HttpClientBuilder.create()
                .setConnectionManager(cm)
                .evictExpiredConnections()
                .build();
    }
    @Override
    public void close() throws IOException {
        if (autoCloseHttpClient) {
            httpClient.close();
        }
    }
// ==================== Builder ====================
    public static class Builder {
        private String systemKey;
        private String privateKey;
        private String baseUrl;
        private String tokenApi;
        private CloseableHttpClient httpClient;
        private ObjectMapper objectMapper;
        private Duration tokenRefreshThreshold;
        public Builder systemKey(String systemKey) {
            this.systemKey = systemKey;
            return this;
        }
        public Builder privateKey(String privateKey) {
            this.privateKey = privateKey;
            return this;
        }
        public Builder baseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
            return this;
        }
        public Builder tokenApi(String tokenApi) {
            this.tokenApi = tokenApi;
            return this;
        }
        public Builder httpClient(CloseableHttpClient httpClient) {
            this.httpClient = httpClient;
            return this;
        }
        public Builder objectMapper(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
            return this;
        }
        public Builder tokenRefreshThreshold(Duration threshold) {
            this.tokenRefreshThreshold = threshold;
            return this;
        }
    public ApiClient build() {
            return new ApiClient(this);
        }
    }
    // ==================== 数据类与异常 ====================
    private static class TokenHolder {
        final String token;
        final Instant expireTime;
        TokenHolder(String token, long expiresInSeconds) {
            this.token = token;
            this.expireTime = Instant.now().plusSeconds(expiresInSeconds);
        }
        boolean isExpiringSoon(Duration threshold) {
            return Instant.now().plus(threshold).isAfter(expireTime);
        }
    }
    public static class ApiException extends RuntimeException {
        public ApiException(String message) { super(message); }
        public ApiException(String message, Throwable cause) { super(message, cause); }
    }
    public static class UnauthorizedException extends ApiException {
        public UnauthorizedException(String message) { super(message); }
    }
    public static class TokenException extends ApiException {
        public TokenException(String message) { super(message); }
        public TokenException(String message, Throwable cause) { super(message, cause); }
    }
    public static class HttpException extends ApiException {
        private final int statusCode;
        public HttpException(int statusCode, String message) {
            super(message);
            this.statusCode = statusCode;
        }
        public int getStatusCode() { return statusCode; }
    }
    public static class SignatureException extends ApiException {
        public SignatureException(String message, Throwable cause) { super(message,
                cause); }
    }
    // ==================== 使用示例 ====================
    public static void main(String[] args) throws Exception {
        String systemKey = "2037470636144144386";
        String privateKey =
                "MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCAH/hiRCZdr5icHtJReY3Qv3c69nvPlzmkDiFUIdi25zg==";
        String baseUrl = "https://gkp.shopec.com.cn/qypro-admin";
        ApiClient client = new ApiClient(systemKey,privateKey,baseUrl);
        try {
            String warningBody = "{\"id\":\"evt- 1001\",\"imei\":\"860001234567890\",\"vin_number\":\"LPS12345678900001\",\"mess_data_type\":\"7\",\"content\":\"{\\\"FenceName\\\":\\\"成都围栏\\\",\\\"MsgAddress\\\":\\\"成都市 高新区天府大道\\\",\\\"IsAlarm\\\":1,\\\"Time\\\":1711440000}\"}";
            // System.out.println("\n=== 获取 Token 示例 ===");
            // String tokenResponse = client.requestWithSignPost("/v1/auth/device/warning-content", warningBody);
            // System.out.println("Token 响应: " + tokenResponse);
            System.out.println("\n=== warning-content Token 模式示例 ===");
            String warningTokenResult = client.post("/v1/auth/device/warning-content",
                    warningBody);
            System.out.println("结果: " + warningTokenResult);
            // System.out.println("\n=== warning-content 签名模式示例(签名头生成)===");
            // Map<String, String> warningSignHeaders =
            //         client.signPost("/v1/auth/device/warning-content", warningBody);
            // System.out.println("签名头: " + warningSignHeaders);
        } finally {
            client.close();
        }
    }
}