HttpClientUtils.java
2.36 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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);
}
}