繁体   English   中英

Spring API 返回文件而不是字符串

[英]Spring API return a file rather than String

我将下面的代码作为 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\"}");
}

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

@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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM