gpt4 book ai didi

spring - 如何读取 Spring Boot Controller 中的发布数据?

转载 作者:行者123 更新时间:2023-12-02 02:35:30 26 4
gpt4 key购买 nike

我想从 Spring Boot Controller 读取 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);
}
}

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

最佳答案

首先,您需要将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);
}
}

关于spring - 如何读取 Spring Boot Controller 中的发布数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48348158/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com