【问题标题】:How do I read the post data in a Spring Boot Controller?如何在 Spring Boot Controller 中读取发布数据?
【发布时间】:2018-06-29 02:40:14
【问题描述】:

我想从 Spring Boot 控制器读取 POST 数据。

我已经尝试了这里给出的所有解决方案:HttpServletRequest get JSON POST data,但我仍然无法读取 Spring Boot servlet 中的发布数据。

我的代码在这里:

package com.testmockmvc.testrequest.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest")
    @ResponseBody
    public String testGetRequest(HttpServletRequest request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}

我尝试过使用收集器作为替代方案,但这也不起作用。我做错了什么?

【问题讨论】:

  • 我总是得到零长度的内容。如果我调试代码,我可以在 servlet 请求对象中看到发布数据,但不知何故它没有被读取。
  • get 请求没有正文,是吗?
  • 澄清:这是一个帖子(不指定方法允许GET和POST)
  • 我只是说你应该用get调用它!

标签: spring spring-boot spring-restcontroller


【解决方案1】:

首先,您需要将 RequestMethod 定义为 POST。 二、可以在String参数中定义@RequestBody注解

@Controller
public class TestRequestController {

    @RequestMapping(path = "/testrequest", method = RequestMethod.POST)
    public String testGetRequest(@RequestBody String request) throws IOException {
        final byte[] requestContent;
        requestContent = IOUtils.toByteArray(request.getReader());
        return new String(requestContent, StandardCharsets.UTF_8);
    }
}

【讨论】:

  • 添加“method=RequestMethod.POST”没有任何区别。我无法将“@ResponseBody”作为注释添加到参数中。我只能将它作为注解添加到方法本身。
  • 我刚刚调整了答案..添加 RequestBody 而不是 ResponseBody 注释,我的错误。
  • 快速更新:我使用相同的方法来处理 GET 和 POST 请求,但是添加 RequestBody 注释需要我有两种不同的方法,一种用于 GET,另一种用于 POST。
猜你喜欢
  • 1970-01-01
  • 2017-10-30
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-04
  • 1970-01-01
  • 2018-10-25
  • 2021-07-19
相关资源
最近更新 更多