现象:
springboot服务接口如下:
@PostMapping(value = "/v1/test")
public String handleBody(@RequestBody String body) {
// TODO something
}
设置Header,"Content-Type: application/x-www-form-urlencoded;charset=utf-8",请求该接口,无论charset使用什么编码,或者接口设置编码decode都是乱码,URLDecoder.decode(body, "UTF-8")
原因:
springboot使用的undertow服务器,并且body内的中文没有进行URLEncoder.encode转码,而服务器中对字节直接强转为char类型导致,详细参考undertow-core包内的,io.undertow.server.handlers.form.FormEncodedDataDefinition。
private void doParse(StreamSourceChannel channel) throws IOException {
// ...
case 2:
if (n == 38) {
this.data.add(this.name, this.builder.toString());
this.builder.setLength(0);
this.state = 0;
} else {
if (n != 37 && n != 43) {
this.builder.append((char)n);
continue;
}
this.state = 3;
this.builder.append((char)n);
}
break;
// ...
}
参考: