[英]How to handle character encoding in spring RestController
I'm trying to find some information on how I should handle character encoding in my RestController
. 我试图找到一些关于如何在
RestController
处理字符编码的RestController
。
Spring seems to completely ignore the charset sent in the Content-Type
header. Spring似乎完全忽略了
Content-Type
标头中发送的字符集。 No matter which charset is sent to the server using this header, the server tries to read it as UTF-8 and sends response with charset UTF-8. 无论使用此标头将哪个字符集发送到服务器,服务器都会尝试将其读取为UTF-8并使用字符集UTF-8发送响应。
Here is a GitHub repository with a demo reproducing this scenario: https://github.com/hawk1234/characterEncodingTest 这是一个GitHub存储库,其中包含一个重现此场景的演示: https : //github.com/hawk1234/characterEncodingTest
Can someone point me where is it described in spring documentation? 有人能指出我在Spring文档中描述的位置吗? I came across Content Negotiation but I think it is more about response format rather then encoding.
我遇到了内容协商,但我认为这更多是关于响应格式而不是编码。
UPDATE 2018-11-01 更新2018-11-01
I've implemented some tests to better show what is the problem. 我已经实施了一些测试,以更好地显示问题所在。 Commit 86dc434351d7ee2c142afc8f389e7837810b19f6 includes class
EncodingTest
which tests endpoint using different encodings. Commit 86dc434351d7ee2c142afc8f389e7837810b19f6包括
EncodingTest
类,它使用不同的编码测试端点。
I've also implemented my encoding handling (Commit a26c5da0b25fba8a40e3be41e967e6b1e5c4d546 ) however it is very basic implementation and may not take all scenarios into account. 我也实现了我的编码处理(Commit a26c5da0b25fba8a40e3be41e967e6b1e5c4d546 ),但它是非常基本的实现,可能不考虑所有场景。 I'm still looking for easier solution using existing libraries.
我仍在寻找使用现有库的更简单的解决方案。
By default charset is UTF-8, MappingJackson2HttpMessageConverter is who manages the charSet. 默认情况下,charset是UTF-8, MappingJackson2HttpMessageConverter是管理charSet的人。 You can override by implementing the bean and setting charSet to null.
您可以通过实现bean并将charSet设置为null来覆盖。
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonConverter.setObjectMapper(objectMapper);
jsonConverter.setDefaultCharset(null);
return jsonConverter;
}
I created a pull request with these changes on your repository pullRequestCharacterEncoding and works well. 我在您的存储库pullRequestCharacterEncoding上创建了一个带有这些更改的pull请求,并且运行良好。 Kind regards.
亲切的问候。
Please try the following in your request: 请在您的请求中尝试以下内容:
Accept-Charset: <US-ASCII or any charset you want to set>
Please check the below link for more details: 请查看以下链接了解更多详情:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset
Please let me know if it works for you 如果它适合您,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.