0

我有一个使用 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);           
    }
}

它按预期工作,但有两个问题:

  1. 当我调用此 API 时,Content-Type 标头是强制性的,我想知道如何使此标头可选。

  2. 如何添加“Accept”标头以支持其他格式,例如 Google Protobuf?

谢谢!

4

1 回答 1

1

如果您不想要求 Content-Type 存在并且是“application/json”,则可以完全省略消耗部分。

“Accept”可通过“produces”值获得,而不是“consumes”。所以如果你想支持 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);
}
于 2013-02-13T22:36:06.637 回答