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.
An example of a basic provider class that implements MessageBodyWriter is as follows:
public class MyProvider implements WriterInterceptor {
public void aroundWriteTo(WriterInterceptorContext ctx) throws IOException,
WebApplicationException {
String customMessage = "This is a custom message";
OutputStream os = ctx.getOutputStream();
WriterInterceptor wraps calls to MessageBodyWriter.writeTo() . that wrapping makes it easy to develop
a MessageBodyWriter solution by simply implementing the aroundWriteTo method.
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();
WebTarget webTarget =" http://localhost:8080/IntroToJavaEE7/rest/simplerest " );
Response res = webTarget.request("text/plain").get();
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.
Search WWH ::

Custom Search