【问题标题】:EntityResponse charset encoding errorEntityResponse 字符集编码错误
【发布时间】:2017-07-14 04:06:09
【问题描述】:

在我的 REST API 中,每当用户尝试访问不存在的资源时,我都会返回 404。

但是,Firefox 不显示“404 错误”页面,而是抱怨字符编码。

这是我的控制器代码:

@RequestMapping("/countries/{countryId}")
public ResponseEntity<?> country(@PathVariable Integer countryId) {
    return countriesService.getCountry(countryId);
}

从服务实体调用此方法:

public ResponseEntity<?> getCountry(Integer countryId) {
    Country country = countryDAO.findById(countryId);
    if (country == null)
        return ResponseEntity.notFound().build();
    return ResponseEntity.ok(new DetailedCountryJson(country));
}

DetailedCountryJson 是一个简单的 json 对象。所以当我访问

localhost:8080/countries/1

我得到了与这个国家相关的 json,但是当我尝试使用不在数据库中的 id 时,我得到了

上面写着

未声明纯文本文档的字符编码。如果文档包含 US-ASCII 范围之外的字符,则文档将在某些浏览器配置中呈现乱码。文件的字符编码需要在传输协议中声明或者文件需要使用字节序标记作为编码签名。

【问题讨论】:

  • 你能把图片中的文字翻译成英文吗?
  • @RickS 我在问题中添加了翻译

标签: java spring rest spring-mvc


【解决方案1】:

您可以使用response.setContentType("text/plain;charset=UTF-8"); 参考这个link

【讨论】:

  • 有什么办法可以用注释来做到这一点吗?我试图将produces = "application/json;charset=UTF-8" 添加到@RequestMapping 中,但我得到了相同的结果
  • 好的,现在可以在服务实体中使用,我刚刚更改了ResponseEntity.notFound().header("content-type", "text/plain; charset=utf-8").build()。谢谢
猜你喜欢
  • 2016-09-14
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多