SpringBoot中如何使用@RequestBody注解接收非JSON字符串参数?
springboot @requestbody 注解接受非 json 字符串参数的方法
在 springboot 中,@requestbody 注解默认接受 json 格式的请求体内容。 当请求体内容为非 json 格式字符串时,可以使用以下方法之一:
方法 1:指定 content-type 头
向请求发送时,在 content-type 头中指定 text/plain 值。这将指示 spring 不将请求体解析为 json。
代码示例:
@postmapping("/sendnews")public string sendcontent(@requestbody(required = false) string lstmsgid) { // …}
方法 2:使用 rawbody 接收器
spring 提供了一个 rawbody 接收器,允许直接访问原始的请求体内容,而无需进行任何解析。
代码示例:
import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class RawBodyController { @PostMapping("/SendNews") public String sendContent(@RequestBody RawBody rawBody) { // rawBody.toString() 返回原始的请求体字符串 // … }}
请注意,使用 rawbody 接收器时需要手动解析请求体内容,并确保其适用于你的应用程序。
以上就是SpringBoot中如何使用@RequestBody注解接收非JSON字符串参数?的详细内容,更多请关注范的资源库其它相关文章!