Jersey Client API in Action

      In one of the previous entries we saw that Jersey provides a Client API for consuming RESTful Web Services. In this entry, we shall see how to use this API and consume the HelloWorld service.

     Before we go ahead and create the client, lets overwrite the HelloResource class with the following code:

@Path("hello")
public class HelloResource { 

    /\*\* Creates a new instance of HelloResource \*/
    public HelloResource() {

    }
 
    /\*\*
     \* Retrieves representation of an instance of
     \*  mycompany.resources.HelloResource
     \* @return an instance of java.lang.String
     \*/
    @GET
    @Produces("text/plain")
    public String sayHello(@QueryParam ("name") String name) {
        if ( name != null ) {
            return "Hello " + name + "!";
        }
        return "Hello World!";
    }
 
    @GET
    @Path("{name}")
    @Produces("text/plain")
    public String sayHello2(@PathParam ("name") String name) {
        return "Hello " + name + "!";
    } 

}

              Deploy the application, once this is done. As you see, what we have tried to do is to define two GET methods, one which reads the query parameter "name" and greets the user accordingly, while the other one reads "name" from the URI path segment and greets the user.

Create the Client Application

              For the illustration purpose, let us create a simple console application, which uses the Jersey Client API to consume the service. Also, we will download the Jersey jar files and use them.

1. In the NetBeans IDE, create a new Java Application, by doing File > New Project > Java > Java Application.

2. Name the Java Application as HelloWorldClient and click the Finish button.

3. Download the required jar files - jersey-client.jar, jersey-core.jar and jsr311-api.jar,  from the links mentioned in the Jersey dependencies page.

4. Add these jar files to the Project library, through Project Properties > Libraries > Add JAR/Folder.

5. Overwrite the main() method with the following code:

public static void main(String[] args) {
        // Create Client and Handle to web resources
        String BASE_URI = "http://localhost:8080/HelloWorldWebapp/resources";
        Client client = Client.create();
        WebResource webResource = client.resource(BASE_URI);

        // send a GET request with Accept header set to "text/plain"
        String response = webResource.path("hello").accept(MediaType.TEXT_PLAIN).get(String.class);
        System.out.println(response);

        // send GET request with a query parameter value for 'name'
        response = webResource.path("hello").queryParam("name", "Pranabh").get(String.class);
        System.out.println(response);

        // send GET request to /hello without any query param
        response = webResource.path("hello").get(String.class);
        System.out.println(response);

        // send GET request to /hello/{name}
        response = webResource.path("hello").path("Ranjita").accept(MediaType.TEXT_PLAIN).get(String.class);
        System.out.println(response);

        // send a GET request and get the response encapsulate in ClientResponse
        ClientResponse clientResponse = webResource.path("hello").get(ClientResponse.class);
        System.out.println(clientResponse.getEntity(String.class));
 }

6. The following import statements need to be added too:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import javax.ws.rs.core.MediaType;

7. Run the application and the following output is seen:

Hello World!
Hello Pranabh!
Hello World!
Hello Ranjita!
Hello World!
 

Lets Dig through the Code

      We created an instance of WebResource using the methods in Client class. Then GET requests were sent to the resources by appending the resource identifier to the web resource handle. Also, in some cases the HTTP Accept header was set using the accept() method. However, in some cases we did not use the accept header, since "text/plain" is the default type.

      Observe the way query parameter name is set in the second GET request. It is set with the value Pranabh, and the response for this request is the string Hello Pranabh!. Similarly, in the fourth GET request, we have passed the value Ranjita for the path segment variable name .

    In the last GET request, we have tried to encapsulate the response in an instance of ClientResponse class instead of String.class as in the previous requests. From this ClientResponse instance we got the response as a String entity.

    All we saw was sending the GET requests, similarly we could send POST, PUT and DELETE methods using the methods post( ), put( ) and delete( ) respectively.

Comments:

Hi All,
I am getting following exception when trying to use REST/HTTP PUT operation with JSON MIME type ( while the same PUT operation works fine for the same REST service)
May 21, 2009 7:16:12 PM com.sun.jersey.json.impl.reader.Jackson2StaxReader getAttributeCount
SEVERE: null
java.io.IOException: Not an attribute, expected primitive value!
at com.sun.jersey.json.impl.reader.Jackson2StaxReader.readNext(Jackson2StaxReader.java:145)
at com.sun.jersey.json.impl.reader.Jackson2StaxReader.getAttributeCount(Jackson2StaxReader.java:301)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector$1.getLength(StAXStreamConnector.java:250)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector$1.getIndex(StAXStreamConnector.java:280)
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor$AttributesImpl.getIndex(InterningXmlVisitor.java:112)
at com.sun.xml.bind.v2.runtime.unmarshaller.XsiTypeLoader.parseXsiType(XsiTypeLoader.java:82)
at com.sun.xml.bind.v2.runtime.unmarshaller.XsiTypeLoader.startElement(XsiTypeLoader.java:67)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:481)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:459)
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:71)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleStartElement(StAXStreamConnector.java:242)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:176)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:360)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:339)
at com.sun.jersey.json.impl.JSONUnmarshaller.unmarshal(JSONUnmarshaller.java:100)
at com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.readFrom(JSONRootElementProvider.java:104)
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:97)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:391)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:81)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityParamInInvoker.getParams(EntityParamDispatchProvider.java:99)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$VoidOutInvoker._dispatch(EntityParamDispatchProvider.java:120)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:154)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:543)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:502)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:493)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:308)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:314)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:239)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:212)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Thread.java:619)
May 21, 2009 7:16:12 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet JerseyRestServlet threw exception
java.lang.NullPointerException
at com.sun.org.apache.xalan.internal.xsltc.trax.SAX2DOM.startElement(SAX2DOM.java:195)
at com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler.closeStartTag(ToXMLSAXHandler.java:204)
at com.sun.org.apache.xml.internal.serializer.ToSAXHandler.flushPending(ToSAXHandler.java:277)
at com.sun.org.apache.xml.internal.serializer.ToXMLSAXHandler.endElement(ToXMLSAXHandler.java:243)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerHandlerImpl.endElement(TransformerHandlerImpl.java:273)
at com.sun.xml.bind.v2.runtime.unmarshaller.DomLoader.leaveElement(DomLoader.java:150)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.endElement(UnmarshallingContext.java:506)
at com.sun.xml.bind.v2.runtime.unmarshaller.InterningXmlVisitor.endElement(InterningXmlVisitor.java:77)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.handleEndElement(StAXStreamConnector.java:217)
at com.sun.xml.bind.v2.runtime.unmarshaller.StAXStreamConnector.bridge(StAXStreamConnector.java:181)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:360)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:339)
at com.sun.jersey.json.impl.JSONUnmarshaller.unmarshal(JSONUnmarshaller.java:100)
at com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider.readFrom(JSONRootElementProvider.java:104)
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.readFrom(AbstractRootElementProvider.java:97)
at com.sun.jersey.spi.container.ContainerRequest.getEntity(ContainerRequest.java:391)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityInjectable.getValue(EntityParamDispatchProvider.java:81)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$EntityParamInInvoker.getParams(EntityParamDispatchProvider.java:99)
at com.sun.jersey.server.impl.model.method.dispatch.EntityParamDispatchProvider$VoidOutInvoker._dispatch(EntityParamDispatchProvider.java:120)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:67)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:154)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:71)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:111)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:63)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:543)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:502)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:493)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:308)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:314)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:239)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:212)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Thread.java:619)

Can anyone help me ?

-Sanju

Posted by sanju on May 21, 2009 at 12:53 PM PDT #

Looks like there has been some changes to the com.sun.jersey.api.client.WebResource class. The method queryParam() that takes a name/value String pair as arguement appears to no longer be present. So the following line is flag as erroneous:

webResource.path("hello").queryParam("name", "Pranabh").get(String.class);

Posted by Osho on June 20, 2009 at 08:04 AM PDT #

Sanju,
I'm sorry for the delayed reply. These comments somehow did not come to my notice.
The stack trace suggests that the JAXB jars are not on the path. I believe you were trying this on JDK 5.0. If you are using JDK 5.0 please add the following dependency, you need not add it if you are using JDK 6.0:
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1</version>
</dependency>

Posted by Naresh on June 28, 2009 at 09:14 PM PDT #

Osho,
the queryParam(String paramName, String paramValue) method still exists. Which version of Jersey are you trying this with?

Posted by Naresh on June 28, 2009 at 09:19 PM PDT #

I have tried with above code. I am getting followin error;

Exception in thread "main" java.lang.NoSuchMethodError: com.sun.jersey.spi.service.ServiceFinder.find(Ljava/lang/String;)Lcom/sun/jersey/spi/service/ServiceFinder;
at com.sun.jersey.api.client.Client.<init>(Client.java:167)
at com.sun.jersey.api.client.Client.<init>(Client.java:139)
at com.sun.jersey.api.client.Client.create(Client.java:466)
at com.muru.NewJerseyClient.main(NewJerseyClient.java:24)

Please do the needful.

Posted by Murugesan on December 16, 2009 at 08:22 PM PST #

Murugesan,

I would need more details:
a. Which version of Jersey did you try this with?
b. Did you try it with the NetBeans wizard? (If so, which version of NetBeans?)

I recommend you post your issue(s) at the Jersey users mailing list users@jersey.dev.java.net, which is a pretty active one, so your issues would not go unnoticed.

Posted by Naresh on December 16, 2009 at 08:34 PM PST #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Naresh worked at Sun Microsystems for two years. During these two years he had worked on the Project Metro and Project Jersey.

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today