SpringCloudHttpUtil.java 4.81 KB
package cn.com.glsx.entmicro.util;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

/**
 * @Description springcloud http工具类
 * @Author yelq
 * @Date 2025/9/18-14:46
 * @Version 1.0
 */
@Slf4j
public class SpringCloudHttpUtil {

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

    public static <T> T post(GSCParam gscParam, Object obj, Class<T> responseType, String method) throws Exception {
        long l = System.currentTimeMillis();
        String url = gscParam.getBaseurl() + method;
        //创建请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        httpHeaders.add("X-App-Id", gscParam.getAppId());
        httpHeaders.add("X-Timestamp", l+"");
        httpHeaders.add("X-Nonce", gscParam.getNonce());
//        httpHeaders.add("X-Mock", "true");// 越过签名校验
        Map<String, Object> params = new HashMap<>();
        params.put("X-App-Id", gscParam.getAppId());
        params.put("X-Timestamp", l);
        params.put("X-Nonce", gscParam.getNonce());
        Map<String, Object> objectMap = getOuterKeyValues(obj);
        params.putAll(objectMap);
        String s = SignUtil.generateSign(params, gscParam.getSecret());
        httpHeaders.add("X-Sign", s);
        HttpEntity<Object> httpEntity = new HttpEntity<>(objectMap, httpHeaders);
        //远程调用,
        log.info("请求地址:{},请求参数:{},请求头:{}", url, JSON.toJSON(obj), httpHeaders);
        T t = restTemplate.postForObject(url, httpEntity, responseType);
        log.info("返回结果:{}", JSON.toJSON(t));
        return t;
    }


    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);
        }
    }

    //

//    public static void main(String[] args) throws Exception {
//        long l = System.currentTimeMillis();
//        //创建请求头
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.add("Content-Type", "application/json");
//        httpHeaders.add("X-App-Id", "dj_zhixin");
//        httpHeaders.add("X-Timestamp", l+"");
//        httpHeaders.add("X-Nonce", "48e5e13229b82c1b4e6e8c96151f0637");
//        DemoRequest demoRequest = new DemoRequest();
//        demoRequest.setCurrent(1);
//        demoRequest.setSize(10);
//        demoRequest.setDog(new DemoRequest.dog("dog", 1));
//        Map<String, Object> objectMap = SpringCloudHttpUtil.getOuterKeyValues(demoRequest);
//        Map<String, Object> params = new HashMap<>();
//        params.put("X-App-Id", "dj_zhixin");
//        params.put("X-Timestamp", l+"");
//        params.put("X-Nonce", "48e5e13229b82c1b4e6e8c96151f0637");
//        params.put("current", 1);
//        params.put("size", 10);
//        params.put("id", 1);
//        params.putAll(objectMap);
//        String s = SignUtil.generateSign(params, "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b");
//        httpHeaders.add("X-Sign", s);
//        HttpEntity<Object> htttpentity = new HttpEntity<>(objectMap, httpHeaders);
////        json.forEach((k, v) -> params.put(k, v));
//        String s1 = new RestTemplate().postForObject("http://192.168.3.145:9898/gsc-vcp-web-facade/test/page/test",
//                htttpentity, String.class);
//        System.out.println(s1);

//        String post = SpringCloudHttpUtil.post(null, demoRequest, String.class, "/test/page/test");
//        System.out.println( post);
//    }

//    @Data
//    @ToString
//    @AllArgsConstructor
//    @NoArgsConstructor
//    public static class DemoRequest {
//        private long current = 1;
//        private long size = 10;
//        private Long id;
//        private List<String> objs;
//        private List<dog> dogs;
//        private dog dog;
//
//        @AllArgsConstructor
//        @NoArgsConstructor
//        @Data
//        public static class dog {
//            private String name;
//            private Integer age;
//        }
//    }
}