Administrator
2026-11-05 adcdcddb3e4a3d1bb22a1cec8f394d2f303ee6e2
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
package com.xcong.excoin.modules.gateApi;
 
import io.gate.gateapi.ApiClient;
import io.gate.gateapi.ApiException;
import io.gate.gateapi.ApiResponse;
import okhttp3.Call;
import okhttp3.Response;
 
import java.io.IOException;
import java.lang.reflect.Type;
 
/**
 * 修复 gate-api SDK 同步请求 Response 未关闭导致 OkHttp 连接泄漏的 ApiClient 子类。
 *
 * <p>SDK 的 {@code ApiClient.execute(Call, Type)} 读取响应体后不调用 {@code response.close()},
 * 触发 OkHttp 连接池 "A connection to ... was leaked. Did you forget to close a response body?" 告警
 * (日志中已多次出现)。本类用 try-with-resources 保证响应在任意路径
 * (成功 / 4xx / 反序列化失败 / IO 异常)都被关闭,行为与 SDK 内置执行完全一致
 * ({@code handleResponse} 为 SDK 公开方法)。</p>
 */
public class GateClosingApiClient extends ApiClient {
 
    /**
     * 重写 SDK 执行逻辑:响应读取完成后强制 close。
     * <ul>
     *   <li>成功路径:反序列化后关闭;</li>
     *   <li>异常路径(handleResponse 抛 ApiException / IOException):try-with-resources 兜底关闭。</li>
     * </ul>
     */
    @Override
    public <T> ApiResponse<T> execute(Call call, Type returnType) throws ApiException {
        try (Response response = call.execute()) {
            T data = handleResponse(response, returnType);
            return new ApiResponse<T>(response.code(), response.headers().toMultimap(), data);
        } catch (IOException e) {
            throw new ApiException(e);
        }
    }
}