HttpClientUtils.java 2.36 KB
package com.diligrp.cashier.mall.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.diligrp.cashier.mall.exception.MallException;
import com.diligrp.cashier.shared.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;

import java.util.Map;

/**
 * @author dengwei
 * @version 1.0.0
 * @ClassName HttpClientUtils.java
 * @Description HttpClientUtils
 * @date 2025-12-24 14:54
 */
public class HttpClientUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);

    /**
     * postJson
     */
    public static String postJson(String url,
                                  Object body,
                                  Map<String, String> header,
                                  String serviceName) {

        try {
            String traceId = IdUtil.fastSimpleUUID();
            log.info("traceId:{},url:{}, body:{}", traceId, url, JsonUtils.toJsonString(body));
            String responseBody = HttpRequest
                    .post(url)
                    .header("content-type", MediaType.APPLICATION_JSON_VALUE)
                    .addHeaders(header)
                    .timeout(60000)
                    .body(JsonUtils.toJsonString(body))
                    .execute()
                    .body();
            if (StringUtils.isBlank(responseBody)) {
                return null;
            }
            log.info("traceId:{},responseBody:{}", traceId, responseBody);
            return responseBody;
        } catch (HttpException e) {
            log.error("http error url:{}", url, e);
            throw new MallException(serviceName + "服务异常!");
        }
    }

    /**
     * postJson
     */
    public static <R> R postJson(String url,
                                 Object body,
                                 Map<String, String> header,
                                 TypeReference<R> jsonTypeReference,
                                 String serviceName) {
        String responseBody = postJson(url, body, header, serviceName);
        if (StringUtils.isBlank(responseBody)) {
            return null;
        }
        return JsonUtils.fromJsonString(responseBody, jsonTypeReference);
    }
}