【问题标题】:Spring POST Fails HTTP 415 and 400Spring POST 失败 HTTP 415 和 400
【发布时间】:2016-04-08 12:53:39
【问题描述】:

我正在尝试使用提琴手对 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": ""
    }
}

payload中的属性与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,但没有帮助。

我还有以下库:

<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.

【问题讨论】:

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


    【解决方案1】:

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

    首先你需要定义请求方法接受 JSON 负载

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

    fiddler 请求应包含标头

    Content-Type: application/json
    

    【讨论】:

    • 我之前试过这个,结果抛出 400 Bad Requst,“客户端发送的请求在语法上不正确。”
    • @varsh 出现 400 的原因是无法将 JSON 解析为 BasicPlanContext 对象。服务器日志中是否有错误跟踪?
    • 我在服务器控制台上没有看到任何日志,除了 SLF4J:无法加载类“org.slf4j.impl.StaticLoggerBinder”。
    • 非常感谢,我得到了日志,上面写着“JsonMappingException:没有找到适合类型 [simple type, class] 的构造函数:无法从 JSON 对象实例化”。以下链接有助于解决内部类的问题:stackoverflow.com/questions/7625783/…
    猜你喜欢
    • 2021-12-18
    • 2013-12-08
    • 2012-07-14
    • 1970-01-01
    • 2012-04-08
    • 2011-08-02
    • 2011-09-09
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多