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

标签 java spring rest

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

相关文章:

java - 具有 Inheritance.JOINED 的 Spring Data Repository

node.js - Express.js 的 Restful API 认证和 session 管理

php - 在 Magento 2 REST Api 中获取所有具有自定义属性的类别

java - java中的final、const和static变量有什么区别

java - Hadoop上下文中Java的内存问题

Spring 数据 Elasticsearch 动态更改 indexName

rest - 路由器、模型或 View ,哪个是发起者

java - 如何在匿名内部类中使用外部方法的输入?

java - 提高 JVM 和 ANT 性能

java - @Cacheable 条件使用应用程序属性