我将httprequest发布到spring boot restful服务器。 ContentType是" application / json; charset = UTF-8"。
我写了一个过滤器来包装HttpServletRequest:
public class WebRequestWrapper extends HttpServletRequestWrapper {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String body;
public WebRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
logger.error("Error reading the request body...");
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
logger.error("Error closing bufferedReader...");
}
}
}
body = stringBuilder.toString();
}
@Override
public ServletInputStream getInputStream() throws IOException {
final StringReader reader = new StringReader(body);
ServletInputStream inputStream = new ServletInputStream() {
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
public int read() throws IOException {
return reader.read();
}
};
return inputStream;
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream(), StandardCharsets.UTF_8));
}
}
我的控制器如下:
@PostMapping(value = "/CustomerRegister")
public RegisterResponse register(@Validated @RequestBody RegisterRequest request) {
log.info("customer register request start! request=[{}]", request);
RegisterResponse response = new RegisterResponse(request.getBussSeqNo(), request.getSysSeqNo());
return response;
}
当请求正文包含英文字母时,一切正常。 但是如果请求体包含中文字符。服务器将抛出异常:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x22
at [Source: java.io.PushbackInputStream@3de12d42; line: 4, column: 14]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x22
at [Source: java.io.PushbackInputStream@3de12d42; line: 4, column: 14]
at [Source: java.io.PushbackInputStream@3de12d42; line: 4, column: 11] (through reference chain: com.ktjr.ktwd.customer.domain.openapi.RegisterRequest["name"])
欢迎任何提示。