我有一个Spring请求映射,默认情况下我想返回XML;如果在请求标头中指定了JSON,则返回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
状态码。Content-Type
指定为
application/xml
我得到正确的XML响应。Content-Type
指定为application/json
,则会收到错误消息
返回:Unexpected '<'
我想要的:
默认情况下从端点返回XML,并在请求中指定返回JSON
编辑
到目前为止,当Postman内部没有发送400 Bad Request
或Accept
时,请求将返回Content-Type
。为了检索所需的响应,我必须将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);
}
答案 0 :(得分:0)
您的示例仍然从请求中提取Content-Type
,而该请求应为Accept
。其次,确保JSON编组器和xml编组器都可对JobResults对象进行序列化。第三,如果您希望请求json是特定行为,则应检查该特定媒体类型,而不是像"*/*"
这样的通用媒体类型。
控制器:
@RequestMapping(value = "/batch/{progName}", method = RequestMethod.GET)
public ResponseEntity<JobResults> processTestObject(@PathVariable("progName") String progName,
@RequestHeader("Accept") MediaType accept) throws Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_XML);
if(!accept.toString().equals("*/*")) {
responseHeaders.setContentType(accept);
}
JobResults response = new JobResults("23423", "result");
return new ResponseEntity<JobResults>(response, responseHeaders, HttpStatus.OK);
}
一些响应对象,但带有注释。
@XmlRootElement
public class JobResults {
String id;
String name;
public JobResults(String id, String name) {
this.id = id;
this.name = name;
}
....
}
通过application/json
标头请求时,以上代码给了我Accept
。