如何发送带有无效响应的标头?

时间:2017-11-01 07:07:46

标签: spring http spring-mvc spring-rest

我正在开发一个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?
}

有没有办法以这种方式发送Location标题?

2 个答案:

答案 0 :(得分:2)

您可以返回如下所示的响应实体:

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

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

答案 1 :(得分:0)

试试这个。它返回您首选的标题和状态,没有正文。

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