乱码问题
java获取http请后后,处理完成返回给前端时,出现乱码。如代码
@RestController
public class RequestBodyController {
@RequestMapping("/save")
public Map content(@RequestBody String content){
Map<String, Object> map1 = new HashMap<>();
map1.put("content", content);
System.out.println(content);
return map1;
//http://localhost:8080/save
}
}
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>解决乱码</title>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$.post("http://localhost:8080/save",
{
name:"你",
age:18,
},
function(data,status){
//data = data.toString()
// alert("数据222: \n" + data+ "\n状态: " + status.code);
alert(data.content)
$("#test1").text(data.content);
});
});
});
</script>
</head>
<body>
<button id="button1">发送一个 HTTP post 请求并获取返回结果</button>
<h3 id="test1"></h3>
</body>
</html>
返回结果
问题原因
java在处理请求时,自动转为Base64的编码形式。
需要将前端请求的字符,使用utf-8解码为正常的字符后再处理
如下:content = java.net.URLDecoder.decode(content,"utf-8");
@RequestMapping("/save")
public Map content(@RequestBody String content) throws UnsupportedEncodingException {
Map<String, Object> map1 = new HashMap<>();
content = java.net.URLDecoder.decode(content,"utf-8");
System.out.println("content=" + content);
map1.put("content", content);
map1.put("xin", "新内容");
return map1;
//http://localhost:8080/save
}
补充:jquery发送的get/post请求默认的编码格式为utf-8
$.get的默认字符编码是urf-8,$.post的默认字符编码是utf-8.
jquery 版本:https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js
java中对url进行编码和解码
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/** 编码Encode后都返回了新的字符串,编码后的字符串不能跨平台,所以要统一制定编码格式
* 需要注意的是在url中 "\" '&' '=' ':' '/'都是具有特殊意义的符号,这些符号一旦被编译后就会失去本身的
* 含义,导致无法被解析,
* 所以在url中需要分块编码,
* 解码Decoder类中decode方法作用是变回成普通字符,其中加号会变成空格,
* */
public class testtest {
public static void main(String[] args) throws UnsupportedEncodingException {
String url = "http://www.baidu.com?name='张三'&age=18 ";
String encodeStr = URLEncoder.encode(url,"UTF-8");
System.out.println(encodeStr);
System.out.println(URLDecoder.decode(encodeStr,"UTF-8"));
}
}