我正在将 spring-boot 从 1.3.6 更新到 2.1.3,而之前响应的内容类型为 application/json;charset=UTF-8
,现在我得到了一个 iso-8859-1 的字符集。
我想要utf 8。
我的 Controller 如下所示:
@Controller
public class MyController {
@RequestMapping(value={"/myService/{serviceId}"}, method=RequestMethod.POST, consumes="application/json")
public ResponseEntity<Void> handlePostServiceId(final InputStream requestInputStream,
@PathVariable String serviceId,
final HttpServletRequest servletRequest,) {
<$businessLogic>
return new ResponseEntity<>(new HttpHeaders(), HttpStatus.ACCEPTED);
}
如果我包含
produces= MediaType.APPLICATION_JSON_UTF8_VALUE
,我可以让它返回 utf-8在我的@RequestMapping
但我只想设置一次,而不是为每个 API 设置一次。我也尝试添加
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
}
按照这里的建议发送到我的 WebMvcConfigurer:https://stackoverflow.com/a/25275291/2855921但这破坏了我使用纯/文本内容类型的可用性 api。
我还确保我的请求是 UTF-8,因此它不仅仅是反射(reflect)我提供的格式。
关于如何将整个项目的字符集设置为 UTF-8 的任何想法?
最佳答案
将以下属性添加到 application.properties 文件:
对于 Spring Boot 1.x
# Charset of HTTP requests and responses. Added to the "Content-Type"
# header if not set explicitly.
spring.http.encoding.charset=UTF-8
# Enable http encoding support.
spring.http.encoding.enabled=true
# Force the encoding to the configured charset on HTTP requests and responses.
spring.http.encoding.force=true
来源:https://docs.spring.io/spring-boot/docs/1.5.22.RELEASE/reference/html/common-application-properties.html对于 Spring Boot 2.x
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force-response=true
来源:https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#server.servlet.encoding.charset
关于spring - 如何使 Spring Boot 默认为 application/json;charset=utf-8 而不是 application/json;charset=iso-8859-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55640629/