如何使用弹簧api的变音符号

时间:2016-07-26 14:51:33

标签: java spring spring-rest

将弹簧片发送到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"])

我还可以添加什么才能使其正常工作?

感谢名单。

2 个答案:

答案 0 :(得分:1)

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

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

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

  • 当您发送JSON时,您需要两者消耗和 生成设置为MediaType.APPLICATION_JSON_UTF8_VALUE
    (应用/ JSON;字符集= UTF-8)。 E.G:

@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>

答案 1 :(得分:0)

其实我接受Yuri Yunikov的回答。

但如果有人使用SOAPui,请不要忘记在那里设置编码请求: like it is described here