java后端返回前端,中文乱码
背景
项目中部分接口,返回到前端后 中文乱码,但是其它接口又是好的。
问题代码
乱码接口:
@RequestMapping("/addComments")
@ResponseBody
public String addComments(@RequestBody TodoCommentRequest request) {
return HttpUtil.doPost(Constant.SVR_HTTP_ADDR + "/todo/addComments", JSON.toJSONString(request));
}
解决办法
1. 加上 produces = {“application/json;charset=UTF-8”}
@RequestMapping(value = "/addComments", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addComments(@RequestBody TodoCommentRequest request) {
return HttpUtil.doPost(Constant.SVR_HTTP_ADDR + "/todo/addComments", JSON.toJSONString(request));
}
2. 返回类型不要用 string
可用 json 或者对象。
@RequestMapping("/addComments")
@ResponseBody
public Object addComments(@RequestBody TodoCommentRequest request) {
return new Gson().fromJson(HttpUtil.doPost(Constant.SVR_HTTP_ADDR + "/todo/addComments", JSON.toJSONString(request)), Map.class);
}
3. 如果无法避免返回 string ,可以指定编码规则
@RequestMapping("/addComments")
@ResponseBody
public Object addComments(@RequestBody TodoCommentRequest request) {
return URLDecoder.decode(HttpUtil.doPost(Constant.SVR_HTTP_ADDR + "/todo/addComments", JSON.toJSONString(request)), CharEncoding.UTF_8);
}
原因
待更新