简体   繁体   中英

How to make Content-Type header optional?

I've an heartbeat API implemeted using Spring REST service:

@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);
}

And MyService.java has below method:

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);           
    }
}

It works as expected but have 2 issues:

  1. When I invoke this API, Content-Type header is mandatory & I want to know how to make this header optional.

  2. How to add "Accept" header so that it can support other format such as Google Protobuf?

Thanks!

If you don't want to require Content-Type exist and be "application/json", you can just omit the consumes section entirely.

"Accept" is available via the "produces" value, as opposed to "consumes." So if you wanted to support Google Protobuf OR application/json, you could do this:

@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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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