代码
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.course.constants.FileFormatConstants;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
@Slf4j
public class AccessServiceUtil {
private static final int REQUEST_BODY_NOT_MATCH_ERROR = 422;
private static <D> HttpResponse post(String serviceName, String serviceUrl, D dto) {
if (StrUtil.isBlank(serviceName) || StrUtil.isBlank(serviceUrl)) {
throw new ServiceException("未获取到服务名, 或服务地址");
}
if (!StrUtil.startWith(serviceUrl, "http")) {
String errorMessage = StrUtil.format("未获取到 {} 服务", serviceName);
throw new ServiceException(errorMessage);
}
log.info("开始访问 {} 服务", serviceName);
long start = System.currentTimeMillis();
String requestBody = JSON.toJSONString(dto);
String contentType = "application/json";
HttpResponse resp = HttpUtil.createPost(serviceUrl).contentType(contentType).body(requestBody).execute();
long end = System.currentTimeMillis();
log.info("访问 {} 服务结束, time = {} ms, isOk = {}", serviceName, (end - start), resp.isOk());
if (!resp.isOk()) {
if (REQUEST_BODY_NOT_MATCH_ERROR == resp.getStatus()) {
log.error("请求参数错误, 应符合 {} 服务要求.", serviceName);
}
log.error("url = {}", serviceUrl);
log.error("requestBody = {}", requestBody);
log.error("responseBody = {}", resp.body());
throw new ServiceException("操作失败, 请联系管理员");
}
return resp;
}
public static <D, R> R postObj(String serviceName, String serviceUrl, D dto, Class<R> resultClass) {
HttpResponse resp = post(serviceName, serviceUrl, dto);
String json = resp.body();
resp.close();
return JSON.parseObject(json, resultClass);
}
public static <D> String postDownload(String serviceName, String serviceUrl, D dto, String dir) {
if (StrUtil.isBlank(dir)) {
throw new ServiceException("未指定存放目录");
}
HttpResponse resp = post(serviceName, serviceUrl, dto);
String fileName = dir + System.currentTimeMillis() + FileFormatConstants.ZIP;
String filePath = RuoYiConfig.getProfile() + fileName;
File file = Paths.get(filePath).toFile();
try (BufferedOutputStream bos = FileUtil.getOutputStream(file)) {
log.info("开始下载 {} 服务返回的文件", serviceName);
bos.write(resp.bodyBytes());
bos.flush();
resp.close();
log.info("完成下载 {} 服务返回的文件", serviceName);
} catch (IOException e) {
log.error(e.getMessage());
throw new ServiceException("操作失败, 无法下载文件");
}
return Constants.RESOURCE_PREFIX + fileName;
}
}