gpt4 book ai didi

java - 如何使 Content-Type header 可选?

转载 作者:行者123 更新时间:2023-12-01 14:50:56 25 4
gpt4 key购买 nike

我有一个使用 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 header 是必需的,我想知道如何将此 header 设为可选。

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

谢谢!

最佳答案

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

“接受”可通过“生产”值获得,而不是“消耗”。因此,如果您想支持 Google Protobuf 或 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);
}

关于java - 如何使 Content-Type header 可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com