繁体   English   中英

如何使Content-Type标头为可选?

[英]How to make Content-Type header optional?

我有一个使用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?

谢谢!

如果您不希望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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM