我有以下控制器:
@RequiredArgsConstructor
@RestController
public class OwnerViewController implements ApiOwnerViewController {
private static final String TEXT_CSV = "text/csv";
private final PrivateOwnerFacade privateOwnerFacade;
@PostMapping("/boat/v1/private-owners/search")
public OwnerViewResponse searchOwners(@Valid @RequestBody SearchOwnersRequest request,
Pageable pageable) {
return privateOwnerFacade.findOwners(request, pageable);
}
@PostMapping(value = "/boat/v1/private-owners/search", produces = TEXT_CSV)
public ResponseEntity<Resource> exportToCsv(@Valid @RequestBody SearchOwnersRequest request, Pageable pageable)
throws IOException {
因此,我有两个映射到相同url的方法,它们都接受POST请求,但生成的内容类型不同-第一个生成application/json
,第二个生成text/csv
。
然后,当我尝试发出请求并设置标头时
Accept: text/csv
我从服务器收到406。
我想知道春天真的有可能做这种事情吗?还是更改第二种方法以使其接受GET
请求的唯一方法?
谢谢
答案 0 :(得分:1)
只需将一个方法与@PostMapping一起使用,返回一个响应实体并动态设置Content-Type-Response-Header。
@RestController
public class TestController {
@GetMapping("/api-endpoint")
public ResponseEntity<String> method(@RequestParam("produces") String produces) {
HttpHeaders responseHeaders = new HttpHeaders();
if (produces.equals("text/csv")) {
responseHeaders.setContentType(new MediaType("text", "csv"));
return new ResponseEntity<String>("foo;bar", responseHeaders, HttpStatus.OK);
} else {
responseHeaders.setContentType(new MediaType("application", "json"));
return new ResponseEntity<String>("{\"foo\": \"bar\"}", responseHeaders, HttpStatus.OK);
}
}
}
答案 1 :(得分:1)
问题是text / csv的请求与两个端点都匹配。
您可以在注释上使用负值,因此第一个将仅匹配非文本/ csv请求:
@PostMapping(value = "/boat/v1/private-owners/search", produces = "!text/csv")
public OwnerViewResponse searchOwners(@Valid @RequestBody SearchOwnersRequest
request,
Pageable pageable) {
return privateOwnerFacade.findOwners(request, pageable);
}
答案 2 :(得分:1)
@RequiredArgsConstructor
@RestController
public class SearchController {
@PostMapping(value = "/search", produces = {APPLICATION_JSON})
public SearchResponse search(@Valid @RequestBody SearchRequest request,
Pageable pageable) {
}
@PostMapping(value = "/search", produces = {TEXT_CSV})
public ResponseEntity<Resource> export(@Valid @RequestBody SearchRequest request, Pageable pageable) throws IOException {
}
}