【问题标题】:How to add content-type header application/json to void postmapping endpoint?如何添加内容类型标头应用程序/json 以取消映射后端点?
【发布时间】:2021-04-07 11:15:52
【问题描述】:

我有一个这样的端点:

@RestController
@RequiredArgsConstructor
@RequestMapping(path = "/api/notifications", produces = APPLICATION_JSON_VALUE)
public class NotificationController {

    @PostMapping
    @ResponseStatus(value = HttpStatus.CREATED)
    public void sendNotification(...) {
        ...
    }
}

在使用协议测试进行测试时,我注意到 api 没有将“application/json”作为 Content-Type 标头返回。我该怎么做呢?

【问题讨论】:

  • 它返回的是哪种内容类型?
  • @RequestMapping(value = "/api/notifications", headers = "Accept=application/json, Content-type=application/json") 。这应该适合你
  • 您不能将void 设为application/json Content-Type,返回一些具有有意义数据的对象,您将获得application/json 标头

标签: java spring spring-boot post content-type


【解决方案1】:

试试这个

    @PostMapping
    public ResponseEntity<Void> sendNotification(...) {
        ...
      return ResponseEntity.status(HttpStatus.CREATED).build();
    }

如果默认情况下 Application/Json 没有返回,那么你可以这样做

return ResponseEntity.status(HttpStatus.CREATED).contentType(MediaType.APPLICATION_JSON).build();

【讨论】:

    猜你喜欢
    • 2020-12-09
    • 1970-01-01
    • 2012-12-16
    • 2017-02-17
    • 2018-07-22
    • 2013-11-17
    • 2022-09-26
    • 1970-01-01
    • 2015-05-29
    相关资源
    最近更新 更多