Spring POST失败HTTP 415和400

时间:2016-04-08 12:53:39

标签: java spring post http-post http-status-code-415

我正在尝试使用fiddler对Spring rest API进行POST调用,

@RequestMapping(value = "/GetPlanByBasicContext/", method = RequestMethod.POST)
public @ResponseBody TravelPlan getPlanByBasicContext(@RequestBody BasicPlanContext b) {
    return planService.getPlan(b));
}

请求小提琴手:

http://localhost:8080/now/travelPlan/GetPlanByBasicContext/

部首:

User-Agent: Fiddler
Host: localhost:8080
Content-Length: 248

POST有效负载:

{
    "sourceLocation": "",
    "destinationLocation": "",
    "modeOfTransport": "car", 
    "travellers": {
        "age1to16": 0,
        "age17to30": 0,
        "age31to50": 0,
        "age50plus": 0
    },
    "dates": {
        "startDate": "",
        "endDate": ""
    }
}

有效负载中的属性与BasicPlanContext类中的属性相同,以及getter和setter。

我收到以下错误:

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

尝试用@ModelAttribute替换@RequestBody,但没有帮助。

我也有以下的libs:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

编辑1: 尝试在标题中添加以下内容,

Content-Type: application/json

关注POST方法,

@RequestMapping(..., headers="Accept=application/json")

这导致400 The request sent by the client was syntactically incorrect.

1 个答案:

答案 0 :(得分:0)

您正在尝试发送JSON有效负载,但服务器拒绝状态为415的请求,表明请求的媒体类型会导致问题。

首先,您需要定义请求方法接受JSON有效负载

@RequestMapping(..., headers="Accept=application/json")

并且fiddler请求应该包含标题

Content-Type: application/json