I am developing a Rest-API application using Java/Quarkus. My POST API accepts XML/JSON contents. I would like to identify the type of MediaType of the incoming data based on which I need to make a request to another URL by setting the appropriate content-type
.
Following is the code I have so far:
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();
}
}
As you can see my input
can be XML/JSON
. If JSON
then I would like to set header("content-type", "application/json")
else if the input
is XML
then I would like to set header("content-type", "application/xml")
.
Based on the content-type
the URL https://example.com/example
calls out a different method to generate the response.
As of now, the function is working accurately for JSON but I am unable to handle the XML Input. Can someone please let me know how can I find the incoming Input MediaType?
I have this question for spring-boot (Find the Content-type of the incoming request in Spring boot) but I am unable to understand how to do it for the Quarkus-based application? Do I need to pass again from front-end or there is some Quarkus default way?
Usually, this is set in the Content-Type
header. So to pull this header you can do this (this uses JAX-RS annotation 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);
}