当发起http调用时,用spring的@RequestBody去接收请求body,导致请求body中的中文乱码,是因为请求过来是用的是UTF-8格式,而@RequestBody默认是用gbk格式去转换的,导致乱码。
可以用去读取Request字节,再转换成UTF-8格式,就不会出现乱码了
@RequestMapping(value = "/testReq", method = RequestMethod.POST)
public Reponse testReq(HttpServletRequest request, @RequestBody Form form) {}
//接收的form出现出现乱码
可以写个方法,直接从HttpServletRequest去读
public static String binaryReader(HttpServletRequest request) {
try {
int len = request.getContentLength();
ServletInputStream iii = request.getInputStream();
byte[] buffer = new byte[len];
iii.read(buffer, 0, len);
//转换成UTF-8格式
return new String(buffer, StandardCharsets.UTF_8);
} catch (IOException e) {
System.out.println("读取请求body异常", e);
}
return "";
}
注意:
request.getInputStream(); request.getReader();和request.getParameter(“key”);这三个函数中任何一个函数执行一次后(可正常读取body数据),之后再执行就无效了。
解决办法 跳转链接