弹簧引导相同的API,但不同的返回类型的字节[]和JSON

发布于 2025-02-06 02:32:53 字数 225 浏览 2 评论 0原文

如果请求Access Accept为type应用程序/JSON,我希望功能能够发送JSON列表,但如果请求标题为type Application/avro,则将其发送为字节数组(AVRO格式)。这应该适用于相同的休息端点,例如 /something /雇员。我可以使用相同的方法,但是不同的返回类型,Spring Boot会查看Accept标头并正确确定要调用哪种方法?

返回类型应该是什么?可以是没有任何类型的响应性吗?

I want the capability to send the JSON list like List if the request Accept Header is of type application/json, but send it in a byte array(avro format) if the request Header is of type application/avro. This should be for the same REST endpoint like /something/employee. Can I have the same method but different return types, will Spring Boot look at the accept header and correctly decide on which method to call?

What should be the return type? Can it be a ResponseEntity without any type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2025-02-13 02:32:55

您可以定义您的方法,以简单地返回naked 响应性并检查Accept标题的值以确定要返回的内容

@GetMapping("/something")
public ResponseEntity getContentNegotiateResponse(@RequestHeader("Accept") String accept) {

    SomeObject someObject = new SomeObject();

    if (accept.equalsIgnoreCase(APPLICATION_JSON_VALUE)) {
        return ResponseEntity.of(Optional.of(someObject));
    } else if (accept.equalsIgnoreCase("application/avro")) {
        byte[] value = "SomeData".getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.of(Optional.of(value));
    } else {
        return ResponseEntity.badRequest().build();
    }
}

You can define your method to simply return a naked ResponseEntity and check the value of the Accept header to determine what to return

@GetMapping("/something")
public ResponseEntity getContentNegotiateResponse(@RequestHeader("Accept") String accept) {

    SomeObject someObject = new SomeObject();

    if (accept.equalsIgnoreCase(APPLICATION_JSON_VALUE)) {
        return ResponseEntity.of(Optional.of(someObject));
    } else if (accept.equalsIgnoreCase("application/avro")) {
        byte[] value = "SomeData".getBytes(StandardCharsets.UTF_8);
        return ResponseEntity.of(Optional.of(value));
    } else {
        return ResponseEntity.badRequest().build();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文