A simple JAX-RS example using @Consumes, @Produces and JAXB

I am trying to create and run a simple JAX-RS example using the annotations @Produces , @Consumes and JAXB.

 @Stateless @LocalBean @Path("/hotel") public class RestMain { @GET @Produces(MediaType.APPLICATION_XML) @Path("{hotelId}") public HotelRESTInfo read(@PathParam("hotelId") long hotelId) { HotelDataSourceFake hotelDataSourceFake = new HotelDataSourceFake(); HotelRESTInfo hotelInfo = hotelDataSourceFake.getFakePlaceById(hotelId); return hotelInfo; } } 

web.xml:

 <servlet> <servlet-name>REST App</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> 

The second application that is the client. Now I have the following client code:

 import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; ... Client client = Client.create(); String uri ="http://localhost:8080/RESTJEE/rest/hotel/" + hotelId; WebResource resource = client.resource(uri); ClientResponse response = resource.accept("application/xml").get(ClientResponse.class); HotelRESTInfo hotelRestInfo = response.getEntity(HotelRESTInfo.class); 

But I do not want to use jersey Client, ClientResponse and WebResource. I want to do this with @Consumes . Should the web.xml client application contain some additional parameters?

Both sides (client and server) contain the HotelRESTInfo class:

 @XmlRootElement public class HotelRESTInfo { ... } 
+4
source share
1 answer

I think you disagree.

You have, on the one hand, HttpClient, which make requests, and on the other, HttpServer, which build answers. This is basic, and I suppose you understand it.

The fact is that the body of the @GET read ()method consumes the body of the request, and creates the body of the response.

So you can have:

 @GET @Consumes(MediaType.APPLICATION_XML) //client sends also xml @Produces(MediaType.APPLICATION_XML) @Path("{hotelId}") public HotelRESTInfo read(@PathParam("hotelId") long hotelId) { (...) } 

Obviously, you want your client to consume web services, so @Consume ultimately makes sense on the client side .

Unfortunately, JaxRS was built on the server side in 2008 or so, without thinking about synergy with the Java client. And @Consumes is finally a server annotation, and I have not seen in the documentation about reusing annotations on the client.

The Jersey client is quite recent, in accordance with the JaxRS 2 specifications. Your questions indicate that these specifications can be difficult to write!

+6
source

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


All Articles