我使用Spring REST服务实现了一个心跳API:
@RequestMapping(value = "heartbeat", method = RequestMethod.GET, consumes="application/json")
public ResponseEntity<String> getHeartBeat() throws Exception {
String curr_time = myService.getCurrentTime();
return Util.getResponse(curr_time, HttpStatus.OK);
}
MyService.java有以下方法:
public String getCurrentTime() throws Exception {
String currentDateTime = null;
MyJson json = new MyJson();
ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
try {
Date currDate = new Date(System.currentTimeMillis());
currentDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(currDate);
json.setTime(currentDateTime);
ObjectWriter writer = mapper.writerWithView(Views.HeartBeatApi.class);
return writer.writeValueAsString(json);
} catch (Exception e) {
throw new Exception("Excpetion", HttpStatus.BAD_REQUEST);
}
}
它按预期工作但有两个问题:
当我调用此API时,Content-Type标头是必需的&amp;我想知道如何使这个标题可选。
如何添加“接受”标题,以便它可以支持其他格式,例如Google Protobuf?
谢谢!
答案 0 :(得分:1)
如果您不希望要求Content-Type存在并且是“application / json”,则可以完全省略使用部分。
“接受”可通过“产生”值获得,而不是“消耗”。因此,如果您想支持Google Protobuf OR application / json,您可以这样做:
@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public ResponseEntity<String> getHeartBeat() throws Exception {
String curr_time = myService.getCurrentTime();
return Util.getResponse(curr_time, HttpStatus.OK);
}