需求背景是这样的,我需要调用第三方的接口,但是第三方提供的接口在他们自己的局域网内,不开放在公网,所以公司的官网是调用不通的,让他们提供VPN,为了安全考虑他们又不肯,好好好,找茬是吧。行,那就自己解决。
我们的项目正式环境是和他们那边在同一个局域网的,而且我们项目可以公网访问,那不就有办法了,我们可以在自己项目上搞一个请求中转的接口,我们将请求发给中转接口,再由中转接口请求他们那边的接口,perfect!
大概就是这样:
本地------------(公网)-------------->中转接口-----------(局域网)----------->第三方接口
实现,使用hutool工具类
1、请求实体:
@Data
public class ThirdInterfaceDTO extends TokenCommonParamDto {
@Schema(description = "请求URL")
@NotBlank(message = "请求URL不能为空")
private String url;
@Schema(description = "请求方式")
@NotBlank(message = "请求方式不能为空")
private String methodType;
@Schema(description = "请求头参数")
private Map<String, String> headers;
@Schema(description = "请求体")
private JSONObject body;
}
2、发起请求:
public JSONObject getThirdInterface(@RequestBody @Validated ThirdInterfaceDTO thirdInterfaceDTO) {
log.info("请求参数:{}", thirdInterfaceDTO);
String methodType = thirdInterfaceDTO.getMethodType();
if (Arrays.stream(Method.values()).noneMatch(item -> StringUtil.equals(item.name(), methodType))) {
throw new BizException("不符合规范的请求类型,请求类型支持GET和POST");
}
HttpRequest httpRequest = HttpUtil.createRequest(StringUtil.equals(methodType, Method.GET.name()) ? Method.GET : Method.POST, thirdInterfaceDTO.getUrl());
if (MapUtil.isNotEmpty(thirdInterfaceDTO.getHeaders())) {
httpRequest.headerMap(thirdInterfaceDTO.getHeaders(), true);
}
JSONObject body = thirdInterfaceDTO.getBody();
if (Objects.nonNull(body) && StringUtils.isNotBlank(body.toJSONString())) {
httpRequest.body(body.toJSONString());
}
String responseBody = httpRequest.execute().body();
return JSONObject.parseObject(responseBody);
}
大功告成!