简体   繁体   English

Java Spring REST Get工作得很好,但是当发布json时我得到404错误

[英]Java Spring REST Get works just fine, but when posting json I get 404 error

I encountered problem with Spring REST web services. 我遇到了Spring REST Web服务的问题。 When I try to post JSON I always get 404 error. 当我尝试发布JSON时,我总是得到404错误。 Get requests works just fine, but post not. 获取请求工作正常,但不发布。 Searched all over the internet but couldn't find similar problem. 在互联网上搜索但找不到类似的问题。 Maybe you guys could help me. 也许你们可以帮助我。 Here is my code: 这是我的代码:

Controller: 控制器:

package com.java.rest;
import com.java.dto.IncomingTemperature;
import com.java.dto.SensorsTemperature;
import com.java.service.GetSensorsTemperature;
import com.java.service.TemperatureService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/rest")
public class TemperatureRestController {

final static Logger logger = LoggerFactory.getLogger(TemperatureRestController.class);

@Autowired
TemperatureService temperatureService;
@Autowired
GetSensorsTemperature sensorService;

@RequestMapping(value = "/temperature", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public ResponseEntity<?> addTemperature(@RequestBody IncomingTemperature temperature){
    logger.info("Temperature: {} recieved", temperature);
    temperatureService.addTemperature(temperature);
    return new ResponseEntity<HttpStatus>(HttpStatus.CREATED);
}

@RequestMapping(value = "/temperature/{sensorId}", method = RequestMethod.GET, produces = "application/json")
public SensorsTemperature getTemperature(@PathVariable("sensorId") Long sensorId){
    logger.info("Getting temperatures for sensor{}", sensorId);
    return sensorService.getSensorsTemperature(sensorId);
}

} }

Model: 模型:

package com.java.dto;


import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;

public class IncomingTemperature implements Serializable{

    private long sensorId;

    private double temperature;

    @JsonFormat(shape= JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss")
    private Date date;

    public long getSensorId() {
        return sensorId;
    }

    public void setSensorId(long sensorId) {
        this.sensorId = sensorId;
    }

    public double getTemperature() {
        return temperature;
    }

    public void setTemperature(double temperature) {
        this.temperature = temperature;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

POM.xml: pom.xml中:

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.java</groupId>
    <artifactId>knowyourheat</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>KnowYourHeat</name>
    <description>Application for temperature monitoring</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Json that I post: 我发布的Json:

{
 "sensorId" : 1,
 "temperture" : 20,
 "date" : "2016-10-20 22:10:10"
}

Edit: 编辑:

Error that i get: 我得到的错误:

 {
  "timestamp": 1477601444227,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/rest/temperature/"
}

Thank you in advance! 先感谢您!

EDIT 2: 编辑2:

I just created new project with the same controller, and everything works just fine. 我刚刚使用相同的控制器创建了新项目,一切正常。 As I found out the problem is with spring security, for some reason even if I permit all requests, Post and Put method doesn't work. 正如我发现问题是弹簧安全性,出于某种原因,即使我允许所有请求,Post和Put方法也不起作用。 So that was my problem. 这就是我的问题。

尝试在@RequestMapping中添加“consumemes =”application / json“,如下所示:

@RequestMapping(value = "/temperature", method = RequestMethod.POST, produces = "application/json", consumes="application/json")

尝试在RequestMapping中添加“headers =”Accept = application / json“”,如下所示:

@RequestMapping(value = "/temperature", method = RequestMethod.POST, headers = "Accept=application/json")

When using @RestController , you don't need @ResponseBody in the methods. 使用@RestController ,方法中不需要@ResponseBody You get 404 because the method can't accept body content of any kind. 你得到404因为该方法不能接受任何类型的身体内容。 When the method only receives content from HTTP Requests, but sends no body content back, you only need consumes . 当该方法仅从HTTP请求接收内容但未发回任何正文内容时,您只需要consumes ResponseEntity<xxx> defines the body content that the method will return in addition to HttpStatus. ResponseEntity<xxx>定义除HttpStatus之外该方法将返回的正文内容。 If it returns no body content and only HttpStatus, ResponseEntity<Void> must be used. 如果它没有返回正文内容而只返回HttpStatus,则必须使用ResponseEntity<Void> Try the following 请尝试以下方法

@RequestMapping(value = "/temperature", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> addTemperature(@RequestBody IncomingTemperature temperature){
    logger.info("Temperature: {} recieved", temperature);
    temperatureService.addTemperature(temperature);
    return new ResponseEntity<Void>(HttpStatus.CREATED);
}

Now you should get the HttpStatus 201 Created on client side. 现在你应该在客户端获得HttpStatus 201 Created

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

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