本文介绍了如何使 spring boot 默认为 application/json;charset=utf-8 而不是 application/json;charset=iso-8859-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 spring-boot 从 1.3.6 更新到 2.1.3,而在响应具有内容类型 application/json;charset=UTF-8 之前,现在我得到了一个字符集 iso-8859-1.

I am updating spring-boot from 1.3.6 to 2.1.3 and while before responses had content type application/json;charset=UTF-8, now I am getting a charset of iso-8859-1.

我想要 utf 8.

我的控制器如下所示:

@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);
}

如果我在 @RequestMapping 中包含 produces= MediaType.APPLICATION_JSON_UTF8_VALUE,我可以让它返回 utf-8,但我只想设置一次,而不是针对每个 API.

I can get it to return utf-8 if I include produces= MediaType.APPLICATION_JSON_UTF8_VALUE in my @RequestMapping but I would like to only have to set that once, rather than for every single API.

我也尝试添加

@Override
    public void configureContentNegotiation(
         ContentNegotiationConfigurer configurer) {
         configurer.defaultContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

按照此处的建议转到我的 WebMvcConfigurer:https://stackoverflow.com/a/25275291/2855921 但那坏了我的可用性 API 使用纯文本/文本内容类型.

to my WebMvcConfigurer as suggested here: https://stackoverflow.com/a/25275291/2855921 but that broke my availability api which consumes plain/text content type.

我还确保我的请求是 UTF-8,所以它不仅仅是镜像我提供的格式.

I also ensured that my request was UTF-8, so it is not just mirroring back the format I gave.

关于如何将整个项目的字符集设置为 UTF-8 的任何想法?

Any ideas on how I can set the charset to be UTF-8 for the entire project?

推荐答案

将以下属性添加到 application.properties 文件:

Add the below properties to the application.properties file:

对于 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 boot 默认为 application/json;charset=utf-8 而不是 application/json;charset=iso-8859-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:17