SpringCloudHttpUtil.java 3.63 KB
package cn.com.glsx.stoassistant.utils;

import cn.com.glsx.stoassistant.config.GSCServicePoolConfig;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Spring Cloud HTTP 工具类
 */
@Slf4j
public class SpringCloudHttpUtil {
    private final static RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
        // 关键点:找到 StringHttpMessageConverter 并将其编码设为 UTF-8
        restTemplate.getMessageConverters()
                .stream()
                .filter(converter -> converter instanceof StringHttpMessageConverter)
                .map(converter -> (StringHttpMessageConverter) converter)
                .forEach(converter -> converter.setDefaultCharset(StandardCharsets.UTF_8));
    }

//    private final static RestTemplate restTemplate = new RestTemplate();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * POST 请求
     */
    public static <T> T post(GSCServicePoolConfig.GSCServiceParam serviceParam, Object obj, Class<T> responseType, String method, String sessionId) throws Exception {
        long timestamp = System.currentTimeMillis();
        if (sessionId != null) {
            method = method + "?sessionId=" + sessionId;
        }
        String url = serviceParam.getBaseurl() + method;

        // 创建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        httpHeaders.add("X-App-Id", serviceParam.getAppId());
        httpHeaders.add("X-Timestamp", timestamp + "");
        httpHeaders.add("X-Nonce", serviceParam.getNonce());

        // 构建参数
        Map<String, Object> params = new HashMap<>();
        params.put("X-App-Id", serviceParam.getAppId());
        params.put("X-Timestamp", timestamp);
        params.put("X-Nonce", serviceParam.getNonce());

        Map<String, Object> objectMap = getOuterKeyValues(obj);
        params.putAll(objectMap);
        if (sessionId != null) {
            params.put("sessionId", sessionId);
        }

        // 生成签名
        String sign = SignUtil.generateSign(params, serviceParam.getSecret());
        httpHeaders.add("X-Sign", sign);

        HttpEntity<Object> httpEntity = new HttpEntity<>(objectMap, httpHeaders);

        // 远程调用
        log.info("请求地址:{},请求参数:{},请求头:{}", url, JSON.toJSON(obj), httpHeaders);
        T result = restTemplate.postForObject(url, httpEntity, responseType);
        log.info("返回结果:{}", JSON.toJSON(result));
        return result;
    }

    /**
     * 获取对象的外层键值对
     */
    public static Map<String, Object> getOuterKeyValues(Object obj) {
        try {
            JsonNode jsonNode = objectMapper.valueToTree(obj);
            Map<String, Object> result = new HashMap<>();

            jsonNode.fields().forEachRemaining(entry -> {
                // 非空才封装
                if (entry.getValue().isNull() || entry.getValue().isMissingNode()) {
                    return;
                }
                result.put(entry.getKey(), entry.getValue());
            });
            return result;
        } catch (Exception e) {
            throw new RuntimeException("JSON转换失败", e);
        }
    }
}