How to get MediaType from a request

I am creating some kind of proxy server with Restlet, however I have a problem that there is no automatic way to determine MediaType based on client request.

Here is my code:

 Representation entity = null; entity.setMediaType(processMediaType(path)); 

To process media type:

 private MediaType processMediaType(String path){ MediaType type = MediaType.ALL; if(path.endsWith("html")){ type = MediaType.TEXT_HTML; } else if (path.endsWith("css")) { type = MediaType.TEXT_CSS; } else if (path.endsWith("js")) { type = MediaType.TEXT_JAVASCRIPT; } else if (path.endsWith("txt")) { type = MediaType.TEXT_PLAIN; } else if (path.endsWith("jpg")){ type = MediaType.IMAGE_JPEG; } else if (path.endsWith("png")){ type = MediaType.IMAGE_PNG; } return type; } 

I was wondering if MediaType can be autoframed (or by getting MediaType from a query that didn't work for me) from the query, so I won’t have to do these if-else statements, which is very limited in catching different types of media.

+1
source share
3 answers

Restlet get the type of request medium based on the Content-Type header. To value you can use this:

 MediaType mediaType = getRequest().getEntity().getMediaType(); 

ClientInfo media type hints correspond to what is provided in the Accept header:

 getRequest().getClientInfo().getAcceptedMediaTypes(); 

To get the header mapping in the Restlet API, you can see this link:

0
source

Why do you need a media type? Usually, when you create rest api in java, you create separate methods for each allowed media type, i.e.

 @Path("<your_path>") @Consumes (MediaType.XML) @Produces (MediaType.XML) public Response processXMLRequest (...){ //a more general method to process all request return processRequest (request, MediaType.XML); } @Path("<your_path>") @Consumes (MediaType.JSON) @Produces (MediaType.JSON) public Response processXMLRequest (...){ //a more general method to process all request return processRequest (request, MediaType.JSON); } 

etc.

+1
source

If you need it, this information is available in the ClientInfo object as part of the request. Using the same mechanisms as Restlet, it is used to negotiate content that Em Ae also responds automatically.

For example, in a function of the ServerResource class:

  List<MediaType> supported = null; MediaType type = getRequest().getClientInfo().getPreferredMediaType(supported); 

If you maintain a list of supported MediaTypes most appropriate way.

+1
source

Source: https://habr.com/ru/post/911422/


All Articles