YYour NameAccount Kit
a9a1b915Add on Jun 10History
/*
 * Copyright (c) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.accountkit.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * HTTP调用工具类
 *
 * @author accountkit
 * @since 2026-04-14
 */
@Slf4j
public class CallUtils {
    /**
     * remoteCall
     *
     * @param request request
     * @return String
     * @throws IOException IOException
     */
    public static String remoteCall(HttpUriRequest request) throws IOException {
        return remoteCall(request, CallUtils::nspErrorHandler);
    }

    /**
     * remoteCallOAuth
     *
     * @param request request
     * @return String
     * @throws IOException IOException
     */
    public static String remoteCallOAuth(HttpUriRequest request) throws IOException {
        return remoteCall(request, CallUtils::oauthErrorHandler);
    }

    /**
     * remoteCallAccountApi
     *
     * @param request request
     * @return String
     * @throws IOException IOException
     */
    public static String remoteCallAccountApi(HttpUriRequest request) throws IOException {
        return remoteCall(request, CallUtils::accountApiErrorHandler);
    }

    /**
     * remoteCall
     *
     * @param request request
     * @param errorHandler errorHandler
     * @return String
     * @throws IOException IOException
     * @throws E E
     */
    public static <E extends Exception> String remoteCall(HttpUriRequest request,
        BiFunction<CloseableHttpResponse, String, E> errorHandler) throws IOException, E {
        try (CloseableHttpResponse response = getClient().execute(request)) {
            HttpEntity responseEntity = response.getEntity();
            String ret = responseEntity != null ? EntityUtils.toString(responseEntity) : null;
            EntityUtils.consume(responseEntity);

            if (errorHandler != null) {
                E error = errorHandler.apply(response, ret);
                if (error != null) {
                    throw error;
                }
            }

            return ret;
        }
    }

    /**
     * toJsonObject
     *
     * @param json json
     * @return JSONObject
     */
    public static JSONObject toJsonObject(String json) {
        Object parse = JSON.parse(json);
        if (parse instanceof JSONObject) {
            return (JSONObject) parse;
        }
        return JSONObject.parseObject(JSONObject.toJSONString(parse));
    }

    /**
     * parseObject
     *
     * @param json json
     * @param clazz clazz
     * @return T
     */
    public static <T> T parseObject(String json, Class<T> clazz) {
        return JSONObject.parseObject(json, clazz);
    }

    /**
     * wrapJsonEntity
     *
     * @param obj obj
     * @return StringEntity
     */
    public static StringEntity wrapJsonEntity(Object obj) {
        return new StringEntity(CallUtils.toJsonString(obj), ContentType.create("application/json", "UTF-8"));
    }

    /**
     * toJsonString
     *
     * @param obj obj
     * @return String
     */
    public static String toJsonString(Object obj) {
        return JSON.toJSONString(obj);
    }

    /**
     * nspErrorHandler
     *
     * @param response response
     * @param rawBody rawBody
     * @return IOException
     */
    public static IOException nspErrorHandler(CloseableHttpResponse response, String rawBody) {
        IOException ex = null;
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            ex = new IOException("call failed! status:" + statusCode + ", response data: " + rawBody);
            return ex;
        }
        Header nspStatus = response.getFirstHeader("NSP_STATUS");
        if (Objects.nonNull(nspStatus)) {
            ex = new IOException("call failed! nsp_status:" + nspStatus.getValue() + ", response data: " + rawBody);
        }
        return ex;
    }

    /**
     * oauthErrorHandler
     *
     * @param response response
     * @param rawBody rawBody
     * @return IOException
     */
    public static IOException oauthErrorHandler(CloseableHttpResponse response, String rawBody) {
        IOException ex = null;
        int statusCode = response.getStatusLine().getStatusCode();
        // http状态码为200,请求成功
        if (statusCode == HttpStatus.SC_OK) {
            return ex;
        }
        // http状态码非200,解析响应的body,业务视情况进行处理
        Map<String, Object> errorResponseBody = CallUtils.toJsonObject(rawBody);
        // 业务响应主错误码
        Object error = errorResponseBody.get("error");
        // 业务响应子错误码
        Object subError = errorResponseBody.get("sub_error");
        // 业务可根据返回的主+子错误码进行自己的业务处理;例:错误码不为空,抛出异常
        if (Objects.nonNull(error) && Objects.nonNull(subError)) {
            ex = new IOException("call failed! http status code: " + statusCode + ", response data: " + rawBody);
        }
        return ex;
    }

    /**
     * accountApiErrorHandler
     *
     * @param response response
     * @param rawBody rawBody
     * @return IOException
     */
    public static IOException accountApiErrorHandler(CloseableHttpResponse response, String rawBody) {
        IOException ex = null;
        int statusCode = response.getStatusLine().getStatusCode();
        // http状态码不是200,请求失败
        if (statusCode != 200) {
            ex = new IOException("call failed! http status code: " + statusCode + ", response data: " + rawBody);
            return ex;
        }

        // http状态码为200,解析响应的body,判断业务错误码
        JSONObject errorResponseBody = CallUtils.toJsonObject(rawBody);
        // 业务响应码
        Integer resultCode = errorResponseBody.getInteger("resultCode");
        // code为0表示成功,非0表示失败
        if (Objects.nonNull(resultCode) && resultCode != 0) {
            ex = new IOException("call failed! http status code: " + statusCode + ", response data: " + rawBody);
            return ex;
        }
        return ex;
    }

    /**
     * getClient
     *
     * @return CloseableHttpClient
     */
    public static CloseableHttpClient getClient() {
        PoolingHttpClientConnectionManager connectionManager = buildConnectionManager(new String[] {"TLSv1.2"},
            new String[] {"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
                "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"});
        connectionManager.setMaxTotal(400);
        connectionManager.setDefaultMaxPerRoute(400);
        RequestConfig config =
            RequestConfig.custom().setConnectionRequestTimeout(100).setRedirectsEnabled(false).build();
        return HttpClients.custom()
            .useSystemProperties()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(config)
            .build();
    }

    private static PoolingHttpClientConnectionManager buildConnectionManager(String[] supportedProtocols,
        String[] supportedCipherSuites) {
        PoolingHttpClientConnectionManager connectionManager = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keyStore = null;
            tmf.init(keyStore);
            sc.init(null, tmf.getTrustManagers(), null);
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sc,
                supportedProtocols, supportedCipherSuites, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("http", new PlainConnectionSocketFactory())
                .register("https", sslConnectionSocketFactory)
                .build();
            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            log.error("build connect manager failed", e);
        }
        return connectionManager;
    }
}