Java Reference
In-Depth Information
WebTarget
objects are immutable, in that methods for altering
WebTarget
s, such as
path
, return new instances of
WebTarget
. This pattern is very similar to the Builder pattern, although there is no
build()
method call.
WebTarget
s
can also be configured by registering features or providers via a call to the target's
register
method, passing either
type of class.
client.register(Feature.class)
client.register(Provider.class)
An example of a basic provider class that implements
MessageBodyWriter
is as follows:
@Provider
public class MyProvider implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException,
WebApplicationException {
String customMessage = "This is a custom message";
OutputStream os = ctx.getOutputStream();
ctx.proceed();
os.write(customMessage.getBytes());
}
}
■
WriterInterceptor
wraps calls to
MessageBodyWriter.writeTo()
. that wrapping makes it easy to develop
a
MessageBodyWriter
solution by simply implementing the
aroundWriteTo
method.
Note
Now let's take a look at how this provider class is registered to a web service client. In the following client, the
MyProvider
interceptor is applied to the client for testing.
public static void main(String[] args){
// Obtain an instance of the client
Client client = ClientBuilder.newClient();
client.register(MyProvider.class);
WebTarget webTarget = client.target("
http://localhost:8080/IntroToJavaEE7/rest/simplerest
"
);
Response res = webTarget.request("text/plain").get();
System.out.println(res.readEntity(String.class));
}
Obtaining a Response
The example at the beginning of this section demonstrated a simple client that returns an XML response. However,
it is possible to return different response types by passing different
String
s or
MediaType
fields to the client target
request method. Table
8-2
lists the different
MediaType
fields that can be used. All fields listed within the table that
contain a
_TYPE
suffix are of type
MediaType
, whereas the others are
static String
types.