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;
public String getSendHeaderBody(String url, HttpHeaders headers) {
try {
HttpEntity<MultiValuedMap<String, Object>> httpEntity = new HttpEntity<>(headers);
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());
}
}
public String getSendHeaderParamBody(String url, HttpHeaders headers, MultiValuedMap<String, Object> params) {
try {
HttpEntity<MultiValuedMap<String, Object>> httpEntity = new HttpEntity<>(params, headers);
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());
}
}
public String getSendParamBody(String url, Map<String, Object> params) {
try {
url = formatUrl(url, params);
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());
}
}
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();
}
public ResponseEntity<String> getSendParamRes(String url, Map<String, Object> params) {
try {
url = formatUrl(url, params);
ResponseEntity<String> getForEntity = restTemplate.getForEntity(url, String.class, params);
return getForEntity;
} catch (Exception e) {
throw new BizException(CommonConstant.ERROR_500, e.getMessage());
}
}
public String postSendBody(String url, HashMap<String, Object> bodyMap) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, 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());
}
System.out.println("------------主前置机返回值---------------:" + postForEntity.getBody()+"");
return postForEntity.getBody();
} catch (Exception e) {
throw new BizException(CommonConstant.ERROR_500, e.getMessage());
}
}
public String postSendHeaderBody(String url, HttpHeaders headers, HashMap<String, Object> bodyMap) {
try {
HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, 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());
}
}
public String postSendHeader(String url, HttpHeaders headers) {
try {
HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(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());
}
}
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);
MultiValueMap<String, Object> resultMap = new LinkedMultiValueMap<>();
resultMap.add(fileName, file);
formatBody(resultMap, body);
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());
}
}
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);
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<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());
}
}
public String postSendMultipartFile(String url, MultipartFile file, String fileName, Map<String, Object> body) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
if (null != file) {
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<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());
}
}
public MultipartFile fileToMultipartFile(File file) throws IOException {
FileItem fileItem = createFileItem(file);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
return multipartFile;
}
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());
}
}
}
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;
@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 自定义全局异常处理
@Slf4j
@RestControllerAdvice(basePackages = {"cn.xx.controller"})
public class GlobalExceptionHandler {
@ExceptionHandler(BizException.class)
public Result<Object> handleServiceException(BizException bizException) {
log.error("发生业务异常,异常编码:{},异常信息:{}", bizException.getCode(), bizException.getMessage());
return Result.error(bizException.getCode(), bizException.getMessage());
}
}
2.3 接口返回数据格式
@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;
@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);
}