Java/Quarkus 如何识别传入请求的Content-type

Java/Quarkus how to identify the Content-type of the incoming request

我正在使用 Java/Quarkus 开发 Rest-API 应用程序。我的 POST API 接受 XML/JSON 内容。我想通过设置适当的 content-type.

来确定传入数据的 MediaType 类型,我需要根据该类型向另一个 URL 发出请求

以下是我目前的代码:

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

@Path("/api")
public class DataGenerator {

    @Path("/generate")
    @POST
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces(MediaType.APPLICATION_JSON)
    public String generateData(String input) throws IOException, InterruptedException {
        final HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/example"))
                .header("content-type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(input))
                .build();
        return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body();
    }
}

如您所见,我的 input 可以是 XML/JSON。如果 JSON 那么我想设置 header("content-type", "application/json") 否则如果 inputXML 那么我想设置 header("content-type", "application/xml").

基于 content-type URL https://example.com/example 调用不同的方法来生成响应。

截至目前,该函数在 JSON 上运行正常,但我无法处理 XML 输入。有人可以告诉我如何找到传入的 Input MediaType 吗?

我有这个关于 spring-boot () 的问题,但我无法理解如何为基于 Quarkus 的应用程序做这个?我需要从前端再次传递还是有一些 Quarkus 默认方式?

通常,这是在 Content-Type header 中设置的。所以要拉这个 header 你可以这样做(这使用 JAX-RS 注释 javax.ws.rs.HeaderParam):

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String hello(@HeaderParam("Content-Type") String contentType, String data) {
        return String.format("Data: %s%nContent-Type: %s", data, contentType);
    }