gpt4 book ai didi

java - 如何在 spring api 中使用变音符号

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:54 24 4
gpt4 key购买 nike

我在向 Spring API 发送变音符号时遇到问题。我想发布以下 JSON:

{
"username": "testümlaut",
"firstName": "test",
"lastName": "Test"
}

为此,我有以下方法开始:

 @RequestMapping(value="/User", method=RequestMethod.POST,
produces={"application/json ; charset=utf-8"}
)
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody User postUser(@RequestBody User user) {

User user = userDao.addUser(user);

return user;
}

如你所见,我确实有一条线:

produces={"application/json ; charset=utf-8"} 

但这并没有帮助。我总是遇到异常(0xfc 是 ü):

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Invalid UTF-8 start byte 0xfc
at [Source: java.io.PushbackInputStream@721e5ed1; line: 2, column: 19] (through reference chain: de.escosautomation.restserver.model.user.UserClone["username"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 start byte 0xfc
at [Source: java.io.PushbackInputStream@721e5ed1; line: 2, column: 19] (through reference chain: de.escosautomation.restserver.model.user.UserClone["username"])

我还可以添加什么来让它发挥作用?

谢谢。

最佳答案

您可以在此处检查几个选项:

  • 在您的应用程序服务器上进行编码。例如,在 Tomcat 上,在所有连接器上确保将 URIEncoding 设置为 UTF-8。例如:

    <Connector port="80" protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="443" URIEncoding="UTF-8"/>

  • 在发送 JSON 时,您需要同时使用和产生设置为 MediaType.APPLICATION_JSON_UTF8_VALUE
    (应用程序/json;字符集=UTF-8)。例如:

@RequestMapping(value="/User", method=RequestMethod.POST,
consumes=MediaType.APPLICATION_JSON_UTF8_VALUE,
produces=MediaType.APPLICATION_JSON_UTF8_VALUE
)

  • web.xml中:

    <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
    <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>

关于java - 如何在 spring api 中使用变音符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com