问题
I am using spring boot in my project and I run some encoding issue.
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){}
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������Ʒ".
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.
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
So How can I use a single spring boot application to support both GBK and UTF-8 encode request.
回答1:
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;
}
回答2:
I had a similar problem and found that Spring Boot has "forceEncoding" enabled by default. This causes the request charset to be overridden and set to UTF-8 every time in their filter.
See Appendix A. Common application properties
The key part is:
Defaults to true when "force" has not been specified.
So setting either
spring.http.encoding.force=false
or
spring.http.encoding.force-request=false
Should solve your problem, as long as the request has the correct headers.
来源:https://stackoverflow.com/questions/39939555/how-to-config-spring-boot-application-to-support-both-utf-8-and-gbk-encode