java - 无法将 JSON 发送到 Spring Boot 应用程序中的其余端点

标签 java json spring maven spring-boot

我必须将 JSON 发送到使用 Spring Boot 构建的其余端服务。我不明白我做错了什么。这是代码

@RestController public class EmailWithTemplate 
{
    @RequestMapping(value="/create-template",method=RequestMethod.GET)
    void CreateTemplate(@RequestBody EmailTemplate emailtemplate)
    {
        System.out.println(emailtemplate.getName());
    } 
}

public class EmailTemplate 
{
    private String name;
    private String body;
    //private String[] values;

    public void setName(String name)
    {
        this.name=name;
    }
    public String getName()
    {
        return name;
    }

    public void setBody(String body)
    {
        this.body=body;
    }
    public String getBody()
    {
        return body;
    }
}

另外,我还在 pom.xml 文件中添加了 jackson 依赖项。

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.13</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

启动tomcat服务器后,当我点击:

localhost:8080/create-template/{"name":"Test", "body":"Test body"}

这显示在浏览器中:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Jan 29 01:58:00 IST 2016 There was an unexpected error (type=Not Found, status=404). No message available

最佳答案

基本上,您的客户端代码会附加 URL localhost:8080/create-template/ 和 JSON {"name":"Test", "body":"Test body"}。因此,您要调用的 URL 是 localhost:8080/create-template/{"name":"Test", "body":"Test body"} 服务器无法找到它,因为服务器只知道 localhost:8080/create-template/资源。这就是您收到 404 的原因。JSON 需要成为请求正文的一部分,而不是请求 URL。

此外,您的服务器正在等待 HTTP GET 请求。 GET 请求不能包含正文。请参阅:HTTP GET with request body

您需要使用 JSON 作为正文执行 HTTP POST 方法。

例如,您应该发送类似以下请求的内容:

POST http://localhost:8080/create-template/ HTTP/1.0
Content-Type: application/json

{
    "name":"Test",
    "body":"Test body"
}

关于java - 无法将 JSON 发送到 Spring Boot 应用程序中的其余端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071390/

相关文章:

java - Spring 和 Jackson ObjectMapper 无法使用自定义过滤器

spring batch ItemReader FlatFileItemReader 将光标设置为从特定行开始读取或动态设置行跳过

java - 在基于 Spring 注解的验证中是否有快捷方式使每个字段都为 @Notempty

c# - 量化垃圾收集与显式内存管理的性能

java - 进行 HTTPS 调用时出现 NullPointerException

java - Android:Java:不使用 GSON 或 jackson 进行 JSON 解析

java - java.lang.NoSuchMethodError:org.springframework.beans.factory.annotation.InjectionMetadata.needsRefresh

java - 使用 Hibernate 在 java 中创建查询 : could not resolve property

带有重音字符的 Java 属性文件

json - 在 swift 中按属性排序和列出 JSON 数组