文章?p>
柯?/h4>
- 1.RestTemplate 工具类
- 2. 一起使用的自定义异常处理
-
- 2.1 自定义异常类
- 2.2 自定义全局异常处理
- 2.3 接口返回数据格式
1.RestTemplate 工具类
package cn.microvideo.module.ycgz.core.util; import cn.hutool.core.collection.CollUtil; import cn.microvideo.module.ycgz.commonconstant.CommonConstant; import cn.microvideo.module.ycgz.exception.BizException; import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.FileSystemResource; import org.springframework.http.*; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.util.UriComponentsBuilder; import javax.annotation.Resource; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; @Component public class FileHttpUtils { @Resource private RestTemplate restTemplate; /** * 根据Header 请求并返回具体内容 * * @param url 请求路径 * @param headers head的参数 * @return 返回结果 */ public String getSendHeaderBody(String url, HttpHeaders headers) { try { // 将请求头部和参数合成一个请求 HttpEntity<MultiValuedMap<String, Object>> httpEntity = new HttpEntity<>(headers); // 发送get请求 ResponseEntity<String> getForEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class); if (getForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, getForEntity.toString()); } return getForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * 根据header 和param 查询接口并返回具体内容 * * @param url 访问路径 * @param headers header 数据 * @param params param数据 * @return 返回结果 */ public String getSendHeaderParamBody(String url, HttpHeaders headers, MultiValuedMap<String, Object> params) { try { // 将请求头部和参数合成一个请求 HttpEntity<MultiValuedMap<String, Object>> httpEntity = new HttpEntity<>(params, headers); // 发送get请求 ResponseEntity<String> getForEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class); if (getForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, getForEntity.toString()); } return getForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * get请求并返回 body 内容 * * @param url 请求地址 * @param params param参数 * @return 返回结果 */ public String getSendParamBody(String url, Map<String, Object> params) { try { url = formatUrl(url, params); // 发送get请求 ResponseEntity<String> getForEntity = restTemplate.getForEntity(url, String.class, params); if (getForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, getForEntity.toString()); } return getForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * 格式化get请求地址 * * @param url * @param params */ public String formatUrl(String url, Map<String, Object> params) { UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); params.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(), o.getValue())); return builder.build().encode().toString(); } /** * get请求并返回 内容 * * @param url 请求地址 * @param params param参数 * @return 返回结果 */ public ResponseEntity<String> getSendParamRes(String url, Map<String, Object> params) { try { url = formatUrl(url, params); // 发送get请求 ResponseEntity<String> getForEntity = restTemplate.getForEntity(url, String.class, params); return getForEntity; } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * psot请求并返回内容 * 根据 body 查询数据 * * @param url 访问路径 * @param bodyMap body 传参 * @return */ public String postSendBody(String url, HashMap<String, Object> bodyMap) { try { // 发送get请求 HttpHeaders headers = new HttpHeaders(); // 设置请求类型 headers.setContentType(MediaType.APPLICATION_JSON); // 将请求头部和参数合成一个请求 HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, headers); // 发送post请求 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); if (postForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, postForEntity.toString()); } System.out.println("------------主前置机返回值---------------:" + postForEntity.getBody()+""); return postForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * psot请求并返回内容 * * @param url 访问路径 * @param headers header 内容 * @param bodyMap body内容 * @return 返回结果 */ public String postSendHeaderBody(String url, HttpHeaders headers, HashMap<String, Object> bodyMap) { try { // 将请求头部和参数合成一个请求 HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, headers); // 发送post请求 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); if (postForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, postForEntity.toString()); } return postForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * post根据header内容获取结果 * 根据header获取数据 * * @param url 访问路径 * @param headers header内容 * @return 返回结果 */ public String postSendHeader(String url, HttpHeaders headers) { try { // 将请求头部和参数合成一个请求 HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(headers); // 发送post请求 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); if (postForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, postForEntity.toString()); } return postForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * post上传单个文件 * * @param url 访问路径 * @param file 上传文件 * @param fileName 文件名 * @return */ public ResponseEntity<String> postSendFile(String url, FileSystemResource file, String fileName, Map<String, Object> body) { try { //封装请求的表头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); //构造请求体,使用LinkedMultiValueMap MultiValueMap<String, Object> resultMap = new LinkedMultiValueMap<>(); resultMap.add(fileName, file); //封装请求参数 formatBody(resultMap, body); //HttpEntity封装整个请求报文 HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(resultMap, headers); //请求接口 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); //返回请求结果 return postForEntity; } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * post 传输多个文件 * * @param url 请求路径 * @param files 文件 * @param fileName 文件名 * @param body 文件内容 * @return 返回结果 */ public String postSendFiles(String url, List<MultipartFile> files, String fileName, Map<String, Object> body) { try { //封装请求的表头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); //构造请求体,使用LinkedMultiValueMap MultiValueMap<String, Object> resultMap = new LinkedMultiValueMap<>(); for (MultipartFile file : files) { ByteArrayResource byteArrayResource = new ByteArrayResource(file.getBytes()) { @Override public long contentLength() { return file.getSize(); } @Override public String getFilename() { return file.getOriginalFilename(); } }; resultMap.add(fileName, byteArrayResource); } //封装请求参数 formatBody(resultMap, body); //HttpEntity封装整个请求报文 HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(resultMap, headers); //请求接口 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); if (postForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, postForEntity.toString()); } return postForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * post上传单个文件 * * @param url 访问路径 * @param file 上传文件 * @param fileName 文件名 * @return */ public String postSendMultipartFile(String url, MultipartFile file, String fileName, Map<String, Object> body) { try { //封装请求的表头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); // 2、封装请求体 MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); //如果文件不存在 if (null != file) { // 将multipartFile转换成byte资源进行传输 ByteArrayResource resource = new ByteArrayResource(file.getBytes()) { @Override public String getFilename() { return file.getOriginalFilename(); } }; //封装文件 param.add(fileName, resource); } else { param.add(fileName, null); } //封装请求参数 formatBody(param, body); //HttpEntity封装整个请求报文 HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers); //请求接口 ResponseEntity<String> postForEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class); //返回请求结果 if (postForEntity.getStatusCodeValue() != HttpStatus.OK.value()) { throw new BizException(CommonConstant.ERROR_500, postForEntity.toString()); } return postForEntity.getBody(); } catch (Exception e) { throw new BizException(CommonConstant.ERROR_500, e.getMessage()); } } /** * 将文件转成MultipartFile * * @param file 源文件 * @return */ public MultipartFile fileToMultipartFile(File file) throws IOException { FileItem fileItem = createFileItem(file); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); return multipartFile; } /** * 封装请求参数 * * @param param * @param body */ public void formatBody(MultiValueMap<String, Object> param, Map<String, Object> body) { if (CollUtil.isNotEmpty(body)) { for (Map.Entry<String, Object> entry : body.entrySet()) { param.add(entry.getKey(), entry.getValue()); } } } /** * MultipartFile 转换的具体实现 * * @param file * @return */ private static FileItem createFileItem(File file) throws IOException { FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem("textField", "text/plain", true, file.getName()); FileInputStream fis = null; OutputStream os = null; int bytesRead = 0; byte[] buffer = new byte[8192]; try { fis = new FileInputStream(file); os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } finally { if (null != fis) { fis.close(); } if (null != os) { os.close(); } } return item; } }
2. 一起使用的自定义异常处理
2.1 自定义异常类
import lombok.Data; /** * @description: 自定义异常类、处理运行时异常 * @author: Mr.Yang * @date: 2022/6/24 15:15 */ @Data public class BizException extends RuntimeException{ private int code; private String message; public BizException(int code, String message) { super(message); this.code = code; this.message = message; } }
2.2 自定义全局异常处理
/** * 自定义全局异常处理 * * @date 2021/10/24 */ @Slf4j @RestControllerAdvice(basePackages = {"cn.xx.controller"}) public class GlobalExceptionHandler { /** * 系统业务异常处理 * * @param bizException 自定义业务异常 * @return 响应实体 * @date 2020/6/9 */ @ExceptionHandler(BizException.class) public Result<Object> handleServiceException(BizException bizException) { log.error("发生业务异常,异常编码:{},异常信息:{}", bizException.getCode(), bizException.getMessage()); return Result.error(bizException.getCode(), bizException.getMessage()); } }
2.3 接口返回数据格式
/**接口返回数据格式 * @author 60974 * * @param <T> */ @Data @ApiModel(value="接口返回对象", description="接口返回对象") public class Result<T> implements Serializable { private static final long serialVersionUID = 1L; /** * 成功标志 */ @ApiModelProperty(value = "成功标志") private boolean success = true; /** * 返回处理消息 */ @ApiModelProperty(value = "返回处理消息") private String message = "操作成功!"; /** * 返回代码 */ @ApiModelProperty(value = "返回代码") private Integer code = 200; /** * 返回数据对象 data */ @ApiModelProperty(value = "返回数据对象") private T result; /** * 时间戳 */ @ApiModelProperty(value = "时间戳") private long timestamp = System.currentTimeMillis(); public Result() { } public Result<T> error500(String message) { this.message = message; this.code = CommonConstant.ERROR_500; this.success = false; return this; } public Result<T> success() { this.message = "成功"; this.code = CommonConstant.OK_200; this.success = true; return this; } public Result<T> success(String message) { this.message = message; this.code = CommonConstant.OK_200; this.success = true; return this; } public static Result<Object> ok() { Result<Object> r = new Result<Object>(); r.setSuccess(true); r.setCode(CommonConstant.OK_200); r.setMessage("成功"); return r; } public static Result<Object> ok(String msg) { Result<Object> r = new Result<Object>(); r.setSuccess(true); r.setCode(CommonConstant.OK_200); r.setMessage(msg); return r; } public static Result<Object> ok(Object data) { Result<Object> r = new Result<Object>(); r.setSuccess(true); r.setCode(CommonConstant.OK_200); r.setResult(data); return r; } public static Result<Object> error(String msg) { return error(CommonConstant.ERROR_500, msg); } public static Result<Object> error(int code, String msg) { Result<Object> r = new Result<Object>(); r.setCode(code); r.setMessage(msg); r.setSuccess(false); return r; } /** * 无权限访问返回结果 */ public static Result<Object> noauth(String msg) { return error(CommonConstant.NO_AUTHZ, msg); }