【问题标题】:Spring API return a file rather than StringSpring API 返回一个文件而不是字符串
【发布时间】:2021-01-26 21:17:31
【问题描述】:

我将下面的代码作为 api 端点。我希望在访问端点时将 json 字符串显示在浏览器上。

但是,当我访问端点时,会下载一个文件。名为 api.json 的文件包含 {"key": "myKey"}。我不知道它为什么会生成一个文件。我能得到一些帮助吗?

谢谢!

@GetMapping(path="/getFields2", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getFieldssec(@Context HttpServletRequest httpServletRequest)
{
    return ResponseEntity.ok("{\"key\": \"myKey\"}");
}

【问题讨论】:

  • 服务器只发送 JSON。然后浏览器决定做什么并决定下载它
  • 使用标题Content-Disposition=inline

标签: java spring endpoint


【解决方案1】:

您可以创建一个Spring Resource 并返回它

@GetMapping(path="/getFields2", produces=MediaType.APPLICATION_JSON_VALUE)
public  ResponseEntity<Resource> getFieldssec(
        @Context HttpServletRequest httpServletRequest) {

    String text="{\"key\": \"myKey\"}";
    Resource resource = new ByteArrayResource(text.getBytes());

    return ResponseEntity.ok()
        .contentLength(text.length())
        .contentType(MediaType.APPLICATION_JSON)
        .body(resource);
}

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2020-04-08
    • 2018-07-03
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2019-11-01
    相关资源
    最近更新 更多