如何发送 header 且响应无效?

How can I send a header with void response?

我正在做一个 Spring 项目。

我正在做这个。

public ResponseEntity<?> create(@RequestBody final Some entity) {
    // persist the entity here
    final URI location = uriComponentsBuilder.path("{id}").buildAndExpand(entity.getId()).toUri();
    return ResponseEntity.created(location).build();
}

我找到了 @ResponseStatus

@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody @NotNull final BaseType entity) {
    // persist the entity here
    // Location header to where?
}

有没有办法用这种方式发送Locationheader?

您可以return响应如下实体:

 return new ResponseEntity<>(location, HttpStatus.CREATED);

HttpHeaders headers = new HttpHeaders();
headers.add(location);
return new ResponseEntity<>(headers, HttpStatus.CREATED);

试试这个。它 returns 您的首选 header 和地位,没有 body.

@ResponseStatus(HttpStatus.I_AM_A_TEAPOT)
@RequestMapping("/teapot")
public HttpHeaders dummyMethod() {
    HttpHeaders h = new HttpHeaders();
    h.add("MyHeader", "MyValue");
    return h;
}