java - Ajax 请求 Spring REST api 415 错误

标签 java angularjs json spring spring-restcontroller

我的 Spring Rest Controller 有问题。 我正在尝试从我的客户端 (angularJS) 发布 (PUT) 数据到我的服务器 (Spring),但每次我尝试发送我收到了 415 Media not supported 错误。

使用 Maven,我已将 jackson-core (2.6.3)jackson-databind (2.6.3) 添加到我的 Spring API。我还使用 @EnableWebMvc 自动将 Jackson 消息转换器添加到 Spring。在我的 Spring Controller 中,我使用 @RestController 来访问 Spring 的 REST 方法。


我的 REST API Controller :

@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public RippleUser updateUserLocation(@PathVariable("id") Integer id, @RequestBody RippleUser user) {
    return user;
}

我尝试过不同类型的消费:

  • MediaType.APPLICATION_JSON_VALUE
  • “应用程序/json”
  • 没有消费
  • 等等

我的 RippleUser 模型 (部分)

@Entity
@Table(name = "user")
@JsonRootName(value = "user")
public class RippleUser implements Serializable {

    @NotNull
    @Column(name = "active", nullable = false)
    private boolean activeUser;

    @Column(name = "latitude", nullable = true)
    private Float lattitude;

    @Column(name = "longitude", nullable = true)
    private Float longitude;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "lastActive", nullable = true)
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy HH:mm:ss")
    private Date timestamp;
}

在这个模型中,我拥有所有必要的 getter 和 setter。


我的 AngularJS 客户端:

 httpService.updateInBackend = function (url, data, callback, errorCallback) {
                http.put(url, data)
                        .then(function successCallback(response) {
                            callback(response.data);
                        }, function errorCallback(response) {
                            errorCallback(response);
                        });
            };

URL: http://server:port/app/location/update/{id}

数据:

params: {
    {
        "user": {
            "latitude": 52.899370,
            "longitude": 5.804548,
            "timestamp": 1449052628407
        }
    }
};

对于此方法,我还将 @JsonRootName(value = "user") 添加到我的 RippleUser 模型中。

我也试过没有用户属性(也从我的模型中删除了它):

params: {
    {
        "latitude": 52.899370,
        "longitude": 5.804548,
        "timestamp": 1449052628407
    }
};

AngularJS HTTP 方法(PUT、POST、DELETE、GET 等)检查参数中的类型并自动设置正确的 header 。


Chrome postman

只是为了确保我也在 Chrome Postman 插件中尝试过这种方法

URL: http://server:port/app/location/update/2

方法: PUT

header : Content-Type:application/json

正文:

{
    "latitude": 52.899370,
    "longitude": 5.804548,
    "timestamp": 1449052628407
}

这给出的错误是:

HTTP Status 415 The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

更新

当我将 @ResponseBody 从 RippleUser 更改为 String 时,我可以在我的 RestController 中接收信息:

@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public RippleUser updateUserLocation(@PathVariable("id") Integer id, @RequestBody String user) {
    return user;
}

我也试过发送一个空的用户对象,但结果是同样的错误信息

下面是我的问题的答案。

最佳答案

这段代码的问题与我预期的有点不同。 415 media not supported 错误由 Spring 抛出,因为它无法用帖子填写所有必填字段。

我的解决方案是添加一个专门供 Spring 使用的类,用于在发送和接收数据时来回转换数据。这个额外类的好处是我可以管理 API 发送和接收的数据。


用户位置

将以下类添加到我的项目中就成功了(使用 getter 和 setter):

public class UserLocation {

    private Float latitude;

    private Float longitude;

    private Date lastActive;
}

此类包含我的 PUT 请求所需的所有数据。 Spring 自动填写所有字段。


Controller

为了完成这项工作,我还必须修改我的 Controller 。新代码如下:

@RequestMapping(value = "/location/update/{id}", method = RequestMethod.PUT)
public UserLocation updateUserLocation(@PathVariable("id") Integer id, @RequestBody UserLocation location) {
    //Find user by ID
    //Add location to user
    //Update the user

    return //the new user
}

希望对大家有帮助

关于java - Ajax 请求 Spring REST api 415 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34067101/

相关文章:

java - 如何获取 'TYPE_3BYTE_BGR' 图像的 RGB 值?

java - 如何制作一个 Eclipse 插件来比较两个文件的文本

angularjs - 由嵌套指令处理的验证输入

java - 如何使用 Dropwizard 读取 JSON 请求正文

javascript - 使用VBA抓取实时数据

java - 地理位置谷歌地图 v2

java - jsp页面报错怎么解决?

javascript - ng-model 和 ng-value 之间有什么区别/不兼容?

javascript - 如何按带有时间戳的日期分组? ( Angular )

java - 显式指定用于读取 JSON 的架构并将缺失的字段标记为 null