如何配置spring boot应用程序以支持UTF-8和GBK编码?

时间:2016-10-09 02:58:41

标签: java encoding utf-8 gbk

我在项目中使用spring boot并且运行了一些编码问题。

在项目中,有一个控制器(下面)接受带有内容类型标题的请求,“application / x-www-form-urlencoded; charset = GBK”。

@RequestMapping(value = "/notify",headers ={"Content-Type=application/x-www-form-urlencoded;charset=GBK"} , method = RequestMethod.POST, produces = "application/x-www-form-urlencoded; charset=GBK")
public ResponseEntity<String> notify(@RequestParam(name = "p") String plain, @RequestParam("s") String signature), HttpServletRequest request){}

当第三方调用这个api时,他们用GBK对请求体进行编码。一旦正文包含中文字符集,我得到的参数是错误的,这不是人类可读的,像这样的结果 ʒ”。

因为客户端使用GBK编码发送请求体,但是spring引导使用UTF-8解码请求体,这是弹簧引导的默认字符集编码。

该项目有不同的第三方,大多数都使用UTF-8,所以我不能通过使用以下命令配置yml文件将项目编码更改为GBK:

spring:
  http:
    encoding:
      charset: GBK
        enabled: true

所以我的第一个想法是扭转我得到的错误的字符串。但是我在下面的测试中失败了。

String para = "p=result中文的&s=ad98adj";
byte[] bytes = para.getBytes("GBK");

ByteChunk byteChunk = new ByteChunk();
byteChunk.setBytes(bytes , 0 , bytes.length);
byteChunk.setCharset(Charset.forName("utf-8"));
String receive = byteChunk.toString();//this is the wrong string

//reverse
byteChunk.reset();
bytes = receive.getBytes("GBK");
byteChunk.setBytes(bytes , 0 ,bytes.length);
byteChunk.setCharset(Charset.forName("GBK"));
receive = byteChunk.toString(); //still the wrong string

那么如何使用单个spring启动应用程序来支持GBK和UTF-8编码请求。

2 个答案:

答案 0 :(得分:0)

添加CharacterEncodingFilter bean可以解决问题,看到表单https://github.com/spring-projects/spring-boot/issues/1182

@Bean
CharacterEncodingFilter characterEncodingFilter() {
    CharacterEncodingFilter filter = new CharacterEncodingFilter();
    filter.setEncoding("UTF-8");
    filter.setForceEncoding(true);
    return filter;
}

答案 1 :(得分:0)

我有一个类似的问题,发现Spring Boot默认情况下启用了“ forceEncoding”。 这将导致请求字符集每次在其filter中被覆盖并设置为UTF-8。

请参见Appendix A. Common application properties

关键部分是:

  

未指定“力”时默认为true。

因此设置

spring.http.encoding.force=false

spring.http.encoding.force-request=false

只要请求具有正确的标头,就可以解决您的问题。