很多项目都是使用ResponseBodyAdvice 来封装统一的reponse接口,
或者进行加密等;
在下载文件的时候,由于返回的是inputstream,类似下面这种封装成Result 的结果是有问题的。
if(mediaType.includes(MediaType.APPLICATION_OCTET_STREAM)){
return body;
}
需要判断 mediaType,然后直接返回;
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {
private static final Logger log = LoggerFactory.getLogger(GlobalResponseBodyAdvice.class);
public GlobalResponseBodyAdvice() {
}
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if(mediaType.includes(MediaType.APPLICATION_OCTET_STREAM)){
return body;
}
HttpHeaders headers = serverHttpResponse.getHeaders();
String requestId = UUID.randomUUID().toString();
if (body instanceof Result) {
((Result)body).setRequestId(requestId);
return body;
} else {
Result result = new Result(body);
result.setRequestId(requestId);
if (body instanceof String) {
serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
return JsonUtil.toFastJson(result);
} else {
return result;
}
}
}
}
网友评论