Java Reference
In-Depth Information
< T > T get ( Class < T > responseType );
< T > T get ( GenericType < T > responseType );
Response get ();
The first two generic get() methods will convert successful HTTP requests to specific Java
types. Let's look at these in action:
Customer customer = client . target ( "" )
. accept ( "application/json" )
. get ( Customer . class );
List < Customer > customer = client . target ( "" )
. accept ( "application/xml" )
. get ( new
new GenericType < List < Customer >>() {});
In the first request we want JSON from the server, so we set the Accept header with the ac-
cept() method. We want the JAX-RS client to grab this JSON from the server and convert it
to a Customer Java type using one of the registered MessageBodyReader components.
The second request is a little more complicated. We have a special MessageBodyReader that
knows how to convert XML into List<Customer> . The reader is very sensitive to the gener-
ic type of the Java object, so it uses the class to obtain in-
formation about the type. GenericType is a sneaky trick that bypasses Java type erasure to
obtain generic type information at runtime. To use it, you create an anonymous inner class
that implements GenericType and fill in the Java generic type you want to pass information
about to the template parameter. I know this is a little weird, but there's no other way around
the Java type system.
WebTarget has additional request() methods whose parameters take one or more String or Medi-
aType parameters. These parameters are media types you want to include in an Accept header. I
think it makes the code more readable if you use the Invocation.Builder.accept() method in-
stead. But this generally is a matter of personal preference.
There's also a get() method that returns a Response object. This is the same Response class
that is used on the server side. This gives you more fine-grained control of the HTTP re-
sponse on the client side. Here's an example:
import ;
Response response = client . target ( "" )
Search WWH ::

Custom Search