【发布时间】:2018-07-06 13:29:25
【问题描述】:
我有一个 Spring 请求映射,我希望默认返回 XML,或者如果在请求标头中指定,则返回 JSON。这是一些代码:
请求映射
@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET, produces = "application/xml)
public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
@RequestHeader("Content-Type") String contentType) throws Exception {
HttpHeaders responseHeaders = MccControllerUtils.createCacheDisabledHeaders();
if(contentType.equals("application/json")) {
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
}
LOGGER.info("Running batch program " + progName);
JobResults response = batchService.processProgName(progName);
return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
}
- 使用没有标头的邮递员,当我点击此端点时,我收到一个
400 Bad Request状态码。 - 在 Postman Headers 字段中,如果我将
Content-Type指定为application/xml我得到了正确的 XML 响应。 - 如果我将
Content-Type指定为application/json我会收到错误 返回:Unexpected '<'
我想要什么:
默认从端点返回 XML,如果在请求中指定则返回 JSON
编辑
到目前为止,当 Postman 中没有发送 Accept 或 Content-Type 时,请求会返回 400 Bad Request。为了检索所需的响应,我必须将Accept 和Content-Type 指定为application/xml
@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET)
public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
@RequestHeader("Content-Type") MediaType contentType) throws Exception {
HttpHeaders responseHeaders = MccControllerUtils.createCacheDisabledHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_XML);
if(!contentType.toString().equals("*/*")) {
responseHeaders.setContentType(contentType);
}
LOGGER.info("Running batch program " + progName);
JobResults response = batchService.processProgName(progName);
return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
}
【问题讨论】: