!57 优化响应工具类 SmartResponseUtil 替换魔法值和移除不必要的异常捕获

Merge pull request !57 from CoderKK/master
This commit is contained in:
1024创新实验室 2025-03-11 07:26:34 +00:00 committed by Gitee
commit 8b40637e98
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F

View File

@ -9,8 +9,10 @@ import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import static cn.hutool.core.util.CharsetUtil.UTF_8;
/**
* 返回工具栏
@ -27,8 +29,8 @@ public class SmartResponseUtil {
public static void write(HttpServletResponse response, ResponseDTO<?> responseDTO) {
// 重置response
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding(UTF_8);
try {
response.getWriter().write(JSON.toJSONString(responseDTO));
@ -44,21 +46,16 @@ public class SmartResponseUtil {
}
public static void setDownloadFileHeader(HttpServletResponse response, String fileName, Long fileSize) {
response.setCharacterEncoding("utf-8");
try {
response.setCharacterEncoding(UTF_8);
if (fileSize != null) {
response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileSize));
}
if (SmartStringUtil.isNotEmpty(fileName)) {
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaTypeFactory.getMediaType(fileName).orElse(MediaType.APPLICATION_OCTET_STREAM) + ";charset=utf-8");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20"));
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20"));
response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}