Java Reference
In-Depth Information
upon. The methods that can be chained to further build the request are
cookie(Cookie)
;
cookie(String, String)
;
header(String, Object)
;
headers(MultivaluedMap<String, Object>)
; and
register
.
Returning Entities
Sometimes there is a requirement to return a type other than
Response
from a web resource. In these cases, it is
possible to obtain an entity type by passing the entity class to the
get
call. The following lines of code demonstrate
how to return a
Jobs
entity, rather than a standard
Response
object:
Client client = ClientBuilder.newClient();
Jobs jobs = client.target("
http://localhost:8080/IntroToJavaEE7/rest/jobsSearch
"
)
.request("application/xml").get(Jobs.class);
System.out.println(jobs.getJobId() + " - " + jobs.getTitle());
In cases where entities are being returned, the request type is required to be
application/xml
or
APPLICATION_XML_TYPE
.
Invoking at a Later Time
There are cases when it makes sense to obtain a request and prepare it for execution but not invoke that request until
a later time. In such cases, you can prepare an
Invocation
that can be executed at a later time. In the following lines of
code, an
Invocation
is created by making a request to a
WebTarget
and then calling the
buildGet
method.
Invocation inv1 = client.target("
http://localhost:8080/IntroToJavaEE7/rest/simplerest
"
)
.request("text/plain").buildGet();
// Sometime later...
Response res = inv1.invoke();
If you were posting a response, the
buildPost
method could be called against the
WebTarget
instead, as shown here:
Invocation inv1 = client.target("
http://localhost:8080/IntroToJavaEE7/rest/makeithappen
"
)
.request("text/plain").buildPost(order);
Response res = inv1.invoke();
■
Note
to asynchronously execute an
Invocation
, call the
invocation submit
method, rather than the
invoke
method.
Invocation objects can be configured similarly to
WebTarget
and
Client
objects. Filters, interceptors, properties,
features, and providers can be configured on an
Invocation
by calling the register method and passing the
appropriate configuration instance, as demonstrated here:
// Assume that inv1 is an Invocation instance
String result = inv1.register(MyInterceptor.class).invoke(String.class);
■
Note
to learn more about filters and interceptors, read the “filters and interceptors” section in this chapter.