Spring REST 服务按预期返回 json,但我被要求下载它而不是显示它的浏览器

Spring REST service is returning json as expected, but I get asked to download it rather than the browser displaying it

我遵循了以下教程:

http://spring.io/guides/gs/rest-hateoas/

这是一个关于使用 Spring 创建超媒体驱动程序 REST 服务的小指南。

我完成了教程,运行 生成的应用程序成功启动。然而,当我点击我的控制器时,浏览器要求我下载或打开文件,而不是仅仅在浏览器中显示它。

有什么想法吗?

编辑:添加控制器代码:

package testingRest;

import org.springframework.hateoas.ResourceSupport;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Greeting extends ResourceSupport
{
    private final String content;

    @JsonCreator
    public Greeting(@JsonProperty("content") String content)
    {
        this.content = content;
    }

    public String getContent()
    {
        return content;
    }
}

回复我:

{"content":"Hello, world!","_links":{"self":{"href":"http://localhost:8080/greeting?name=world"}}}

您需要安装浏览器extension/plugin。浏览器默认不支持 json 格式。

由于您只使用 JSON 字符串,因此您需要将 HTTP Header Content-Type 设置为 application/json

所以在你的控制器中,你需要有以下内容来设置内容类型

response.setContentType("application/json");

Firefox 对空 JSON 回复的默认响应是保存而不是显示。 Chrome 将 JSON 显示为文本,我使用 Firefox 的 RESTClient 扩展来处理 JSON API(它允许您设置和检查其他 headers 并提供请求 body)。