如何配置Spring Boot应用程序以支持UTF-8和GBK编码? [英] How to config spring boot application to support both UTF-8 and GBK encode?

查看:1654
本文介绍了如何配置Spring Boot应用程序以支持UTF-8和GBK编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用spring boot,并且遇到了一些编码问题.

I am using spring boot in my project and I run some encoding issue.

在项目中,下面有一个控制器,它接受带有内容类型标头"application/x-www-form-urlencoded; charset = GBK"的请求.

In the project, there is a controller(below) which accept request with a content type header ,"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编码请求主体.一旦主体包含中文字符集,我得到的参数是错误的,这是人类无法读取的,类似于result Ʒ".

When the third party invoke this api ,they encode the request body by GBK.Once the body contain Chinese charsets,the parameter I got is wrong,which is not human readable, something like this "result������Ʒ".

因为客户端使用GBK编码发送请求主体,但是Spring Boot使用UTF-8解码请求主体,这是Spring Boot的默认字符集编码.

Because the client send the request body with GBK encode,but the spring boot decode the request body with UTF-8 which is the default charset encode of spring boot.

该项目有不同的第三方,其中大多数使用UTF-8,因此我无法通过使用以下命令配置yml文件来将项目编码更改为GBK:

The project is available different third-parties,most of them are using UTF-8,so I can not change the project encode to GBK by config the yml file with the following:

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

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

So my first thought is to reverse the wrong string I got.But I fail with the following test.

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 boot应用程序来支持GBK和UTF-8编码请求.

推荐答案

添加CharacterEncodingFilter bean可以解决此问题,请参见

Adding the CharacterEncodingFilter bean can solve the problem ,seeing form 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;
}

这篇关于如何配置Spring Boot应用程序以支持UTF-8和GBK编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆