Spring Boot控制器可以接收纯文本/文本吗?

rub*_*bmz 5 java rest spring spring-boot

我正在尝试处理带有纯文本(utf-8)正文的 POST 请求,但 spring 似乎不喜欢调用的纯文本性质。可能是它不受支持 - 或者是我编码错误?

@RestController
@RequestMapping(path = "/abc", method = RequestMethod.POST)
public class NlpController {
    @PostMapping(path= "/def", consumes = "text/plain; charset: utf-8", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Object> doSomething(@RequestBody String bodyText)
    {
        ...
        return ResponseEntity.ok().body(responseObject);
    }
}
Run Code Online (Sandbox Code Playgroud)

回应是:

已解决 [org.springframework.web.HttpMediaTypeNotSupportedException:不支持内容类型“application/x-www-form-urlencoded”]

我用curl命令测试:

curl -s -X POST -H 'Content-Type: text/plain; charset: utf-8' --data-binary @text.txt localhost:8080/abc/def
Run Code Online (Sandbox Code Playgroud)

text.txt 包含纯文本(希伯来语中的 UTF-8)。

小智 -1

@rumbz 请参考下面的链接它可能会解决您的问题

@RequestBody MultiValueMap 不支持内容类型“application/x-www-form-urlencoded;charset=UTF-8”

1 使用注释

@RequestMapping(value = "/some-path", produces = 
org.springframework.http.MediaType.TEXT_PLAIN)    
public String plainTextAnnotation() {    
    return "<response body>";    
}
Run Code Online (Sandbox Code Playgroud)

将 /some-path 替换为您想要使用的任何路径。

2 在响应实体的 HTTP 标头中设置内容类型:

public String plainTextResponseEntity() {    
     HttpHeaders httpHeaders = new HttpHeaders();    
     
     httpHeaders.setContentType(org.springframework.http.MediaType.TEXT_PLAIN);    
     return new ResponseEntity("<response body>", httpHeaders, HttpStatus.OK);    
}  
Run Code Online (Sandbox Code Playgroud)