【问题标题】:Java Spring Restcontroller PostJava Spring Restcontroller 发布
【发布时间】:2015-07-30 07:41:23
【问题描述】:

我需要帮助创建对我的 Java Spring Restcontroller 的 POST 请求。

这是我的控制器 -

@RestController
@RequestMapping("hedgesimulator/")
public class HedgeSimulatorController {

    @RequestMapping(value = "hedgesim/", method = RequestMethod.POST)
    @ResponseBody
    public HedgeSimulatorLog putHedgeSimulation(
        @RequestBody HedgeSimulatorLog hedgeSimulatorLog) {

        System.out.println(hedgeSimulatorLog.toJsonString());
        return hedgeSimulatorLog;
    }
}

我正在使用 Chrome 的“Advanced Rest Client”插件将我的请求发布到我的 URL(我确定我的 localhost 运行正常,等等)

我需要在标题中添加什么?

我收到“HTTP 400 - 状态报告:客户端发送的请求在语法上不正确”的错误

请帮忙!

【问题讨论】:

  • 您可能希望将 Spring MVC 日志记录级别设置为 DEBUG,并检查您的服务器访问日志以获取有关正在发出的请求的更多信息。听起来请求是错误的 - 也可以尝试使用 curl 或其他命令行工具发出请求。最后,我认为@ResponseBody@RestController 中是多余的。
  • 我认为请求有效负载无法转换为 HedgeSimulatorLog bean。您可以发布 HedgeSimulatorLog bean 和示例 JSON 有效负载吗?

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


【解决方案1】:

您可以进行以下检查。

  1. 通过一些在线工具验证您发送的请求正文,例如 JSonLint
  2. 检查MappingJackson2HttpMessageConverter是否已注册。默认情况下,如果类路径中有 jar,Spring 会注册此转换器。
  3. 如果您使用的是@RestController,则无需使用@ResponseBody。所以删除它。

有关使用Spring 4.0 创建和使用 REST 服务的完整示例,您可以访问Techno Spots

【讨论】:

    【解决方案2】:

    尝试以下方法,希望您能解决问题:

    1. 由于你使用的是@RestController注解,所以不需要再次使用@ResponseBody注解,这是多余的。

    2. 如果您使用的是 Spring Boot,请确保您已添加以下依赖项。

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      
    3. 如果项目不是spring boot,则为jackson添加依赖:com.fasterxml.jackson.databind.ObjectMapper

    4. 1234563 JSON 数据。

    希望,它会有所帮助。

    【讨论】:

      【解决方案3】:

      @RequestMapping(value = "/hedgesim/", method = RequestMethod.POST)

      【讨论】:

        【解决方案4】:

        要将对象传递给控制器​​,您必须配置 HttpMessageConverter 来保存该对象的序列化和反序列化。例如,如果要将对象作为 JSON 传递给控制器​​,请在 spring 配置文件中的 mvc 声明中设置 MappingJackson2HttpMessageConverter 作为参数。

        <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </mvc:message-converters>
        </mvc:annotation-driven>
        

        如果http消息转换器配置正确,可能请求格式不正确。

        【讨论】:

          猜你喜欢
          • 2017-10-15
          • 2019-01-01
          • 2020-09-27
          • 2018-11-20
          • 2020-06-23
          • 2020-10-02
          • 2015-11-17
          • 2015-07-02
          • 1970-01-01
          相关资源
          最近更新 更多