37.2. Sharing an interface between client and server
It is usually possible to share an interface between the client and server. In the previous scenario, your JAX-RS services must implement an annotated interface, then reuse that same interface to create client proxies to invoke on the client side. However, this is limited when your JAX-RS methods return a Response object. This is problematic because, in a raw Response return type declaration, the client has no type information. There are two ways to work around this problem. The first is to use the
@ClientResponseType
annotation.
import org.jboss.resteasy.annotations.ClientResponseType; import javax.ws.rs.core.Response; @Path("/") public interface MyInterface { @GET @ClientResponseType(String.class) @Produces("text/plain") public Response get(); }
This will not always work, because some
MessageBodyReader
s and MessageBodyWriter
s need generic type information in order to match and service a request.
@Path("/") public interface MyInterface { @GET @Produces("application/xml") public Response getMyListOfJAXBObjects(); }
In this case, your client code can cast the returned Response object to a
ClientResponse
and use one of the typed getEntity()
methods.
MyInterface proxy = ProxyFactory.create(MyInterface.class, "http://localhost:8081"); ClientResponse response = (ClientResponse)proxy.getMyListOfJAXBObjects(); List<MyJaxbClass> list = response.getEntity(new GenericType<List<MyJaxbClass>>());