RESTful Java client with Jersey client

This tutorial show you how to use Jersey client APIs to create a RESTful Java client to perform “GET” and “POST” requests to REST service that created in this “Jersey + Json” example.

1. Jersey Client Dependency

To use Jersey client APIs, declares “jersey-client.jar” in your pom.xml file.

File : pom.xml


	<dependency>
		<groupId>com.sun.jersey</groupId>
		<artifactId>jersey-client</artifactId>
		<version>1.8</version>
	</dependency>

2. GET Request

Review last REST service.


@Path("/json/metallica")
public class JSONService {

	@GET
	@Path("/get")
	@Produces(MediaType.APPLICATION_JSON)
	public Track getTrackInJSON() {

		Track track = new Track();
		track.setTitle("Enter Sandman");
		track.setSinger("Metallica");

		return track;

	}
	//...

Jersey client to send a “GET” request and print out the returned json data.


package com.mkyong.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientGet {

  public static void main(String[] args) {
	try {

		Client client = Client.create();

		WebResource webResource = client
		   .resource("http://localhost:8080/RESTfulExample/rest/json/metallica/get");

		ClientResponse response = webResource.accept("application/json")
                   .get(ClientResponse.class);

		if (response.getStatus() != 200) {
		   throw new RuntimeException("Failed : HTTP error code : "
			+ response.getStatus());
		}

		String output = response.getEntity(String.class);

		System.out.println("Output from Server .... \n");
		System.out.println(output);

	  } catch (Exception e) {

		e.printStackTrace();

	  }

	}
}

Output…


Output from Server .... 

{"singer":"Metallica","title":"Enter Sandman"}

3. POST Request

Review last REST service.


@Path("/json/metallica")
public class JSONService {

	@POST
	@Path("/post")
	@Consumes(MediaType.APPLICATION_JSON)
	public Response createTrackInJSON(Track track) {

		String result = "Track saved : " + track;
		return Response.status(201).entity(result).build();
		
	}
	//...

Jersey client to send a “POST” request, with json data and print out the returned output.


package com.mkyong.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

	try {

		Client client = Client.create();

		WebResource webResource = client
		   .resource("http://localhost:8080/RESTfulExample/rest/json/metallica/post");

		String input = "{\"singer\":\"Metallica\",\"title\":\"Fade To Black\"}";

		ClientResponse response = webResource.type("application/json")
		   .post(ClientResponse.class, input);

		if (response.getStatus() != 201) {
			throw new RuntimeException("Failed : HTTP error code : "
			     + response.getStatus());
		}

		System.out.println("Output from Server .... \n");
		String output = response.getEntity(String.class);
		System.out.println(output);

	  } catch (Exception e) {

		e.printStackTrace();

	  }

	}
}

Output…


Output from Server .... 

Track saved : Track [title=Fade To Black, singer=Metallica]

Download Source Code

Download it – Jersey-Client-Example.zip (8 KB)

References

  1. JSON example with Jersey + Jackson
  2. Jersey client examples
  3. RESTful Java client with RESTEasy client framework
  4. RESTful Java client with java.net.URL
  5. RESTful Java client with Apache HttpClient

74 comments on “RESTful Java client with Jersey client

  1. I am getting response from rest service and able to view as,
    log.debug(“rest service response” + response.getEntity(String.class));

    but when I capture the response in String Variable,

    String output = response.getEntity(String.class);
    System.out.println(“the output is: ” + output);

    Output variable is having null value. Using jersey-client-1.19.4.jar

    Reply
  2. String input = “{\”singer\”:\”Metallica\”,\”title\”:\”Fade To Black\”}”;
    ClientResponse response = webResource.type(“application/json”)
    .post(ClientResponse.class, input);

    Here You stored a simple data in String input. And pass that simple data(“String input”) as a POST request to the server.
    My Question is :— 1) first, I store my xml data in a XML file .
    2) I want to pass that xml data trough my XML file to the server as a POST request.
    I tried below given code but its not woking
    ClientResponse response = webResource.type(“MediaType.APPLICATION_XML”).entity(new File(“C:\\MyXml.xml”)
    .post(ClientResponse.class);
    So how can i read my xml data from my XML file in jersey client.? Ans transfer that xml data to server as a POST request to getting a correct response from server…?

    Reply
  3. how to set connection timeout on Web Application Server? I tried w”client.setConnectTimeout(0); and client.setConnectTimeout(600000);” which did not work. Webservice I hit takes more than 10 mins but the caller application connection timesout in 5 mins. Can someone help?

    Reply
  4. Thanks so much, let me show a better way to convert object to json in post using JACKSON:

    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.ObjectWriter;

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(objectInput);

    Hugs!

    Reply
  5. String input = “{\”singer\”:\”Metallica\”,\”title\”:\”Fade To Black\”}”;
    In this line we are hardcoding stuff.
    But how to put dynamic content. I tried with “{\”+xyz+”\” which doesnt work.. can any1 help. Thanks in advance

    Reply
  6. How to parse the output to get only specific values alone from the response.i.e get only singer attribute.

    Reply
  7. Hi, I have setup all but still getting this error at the time of compiling class, Please help!

    =====================
    Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/jersey/spi/inject/Errors$Closure
    at com.prefme.services.JerseyClientPost.main(JerseyClientPost.java:15)
    Caused by: java.lang.ClassNotFoundException: com.sun.jersey.spi.inject.Errors$Closure
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    … 1 more
    ====================

    Reply
  8. this is sample that jersey version is v2.26.
    how can i do coding that jersey version is v2.25.1?
    v2.25.1 has not WebResource package.

    jersey v2.25.1 of servlet-class is ” org.glassfish.jersey.servlet.ServletContainer “.

    Reply
  9. Hi Mkyong,

    When i am saving data to the to the server database using web services using jersey like your second example in my live example in project development i am facing 2 issues:

    javax.ws.rs.ProcessingException: Unable to invoke request
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invok
    e(ApacheHttpClient4Engine.java:287)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invok
    e(ApacheHttpClient4Engine.java:283)
    … 9 more
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)

    Bellow is my sample code:

    inputStream = Olis.class.getClassLoader().getResourceAsStream(propFileName);
    try {
    prop.load(inputStream);
    } catch (IOException e) {
    e.printStackTrace();
    }
    String docitURL = prop.getProperty(“docit.url”);
    String docitAuthToken = prop.getProperty(“docit.authToken”);
    if (extracted(inputStream) != null) {
    prop.load(extracted(inputStream));
    } else {
    throw new FileNotFoundException(“property file ‘” + propFileName + “‘ not found in the classpath”);
    }

    String tempURL = docitURL + “token=” + docitAuthToken;

    System.out.println(“url: “+tempURL);
    Client client = ClientBuilder.newClient();
    Response response = client.target(tempURL).request(MediaType.APPLICATION_JSON)
    .post(Entity.entity(lr, MediaType.APPLICATION_JSON), Response.class);

    if (response.getStatus() == Status.CREATED.getStatusCode() || response.getStatus() == Status.NO_CONTENT.getStatusCode())
    return true;
    else
    return false;

    Reply
    1. I this above exception how could i add timeOut to server

      Reply
  10. Really a nice example to understand the get and post difference in client and server . Thank u so much .

    Reply
  11. can you please move to the latest version of Jersey 2.X. The examples are good, but 2.X have entirely different set of APIs.

    Reply
  12. How do I add basic authorization to a header? I tried this but it returns error 500:

    Client client = Client.create();
    WebResource webResource = client.resource(“http://url/search”);

    MultivaluedMapImpl values = new MultivaluedMapImpl();
    values.add(“max”, “2”);
    values.add(“table”, “abc”);

    ClientResponse response = webResource.header(HttpHeaders.AUTHORIZATION, “Basic ” + “GVFUCVJFT1BTOkJORjhXMkZQVjloa1BFYQ==”)
    .accept(MediaType.APPLICATION_XML)
    .type(MediaType.APPLICATION_FORM_URLENCODED)
    .post(ClientResponse.class, values);

    Any thoughts?

    Reply
  13. Hi, i receive this error when i import..

    import com.sun.jersey.api.client.ClientResponse;

    The type javax.ws.rs.ext.RuntimeDelegate$HeaderDelegate cannot be resolved. It is indirectly
    referenced from required .class files

    Has anyone came across this issue? And i am using jersey-client-1.18.3.jar

    Reply
  14. Hi Mkyong,

    I am getting below compile time error while consuming the webservice. I am using jersey-client-1.8.jar.

    “The method accept(MediaType[]) in the type WebResource is not applicable for the arguments (String)”

    Can you please help me to resolve this issue.

    Reply
  15. Hi All use this additional dependency to fix the below issue.

    –issue
    java.lang.RuntimeException: Failed : HTTP error code : 404

    at com.mkyong.client.JerseyClientPost.main(JerseyClientPost.java:24)

    –dependency

    com.sun.jersey

    jersey-server

    1.8

    Reply
  16. Hello!,

    GET request is working
    http://localhost:8080/RESTfulExample/rest/json/metallica/post is not.
    “The specified HTTP method is not allowed for the requested resource.”
    Also, I see “This element neither has attached source nor attached Javadoc and hence no Javadoc could be found” description when mouse hovers over javax.ws.rs.core.MediaType;

    Can anyone help me please?

    Reply
  17. hi,
    I have a RESTFul OSB service with HTTP method as POST, this service is deployed on web logic server and I have the WADL file for this service. Now I want to invoke this OSB service in my java code by posting a request input xml file. Kindly suggest a possible solution for. Please reply as soon as possible as this is urgent.

    Reply
  18. Hi,

    I do:

    ClientResponse response = webResource.type(“application/json”).accept(“application/json”).post(ClientResponse.class, input);

    Is correct?

    Reply
  19. Hi,

    Please, help me:

    ClientResponse response = webResource.type(“application/json”)

    .post(ClientResponse.class, input);

    if (response.getStatus() != 201) {

    throw new RuntimeException(“Failed : HTTP error code : ”

    + response.getStatus());

    }

    Exception:

    ago 14, 2014 8:56:19 PM com.sun.jersey.spi.container.ContainerResponse write

    SEVERE: The registered message body writers compatible with the MIME media type are:

    application/octet-stream ->

    Help me please!

    Reply
  20. What if a webservice consumes and produces JSON object?

    Reply
  21. Dear All,

    I run the file JerseyClientGet.java and got following error:

    “java.lang.RuntimeException: Failed : HTTP error code : 401

    at com.mkyong.client.JerseyClientGet.main(JerseyClientGet.java:21)”

    I got the error when running file JerseyClientPost.java

    Could anyone please advice?

    Reply
  22. Thanks so much for this! I think this is exactly what I need! I will return to let you know if it works for me! Thanks!

    Reply
  23. Get the following errors when deploying to running in JBoss with JBoss Developers studios-

    11:25:14,985 INFO [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of “RESTfulExample.war”
    11:25:15,511 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015960: Class Path entry jaxb-api.jar in /C:/Program Files/EAP-6.0.1/jboss-eap-6.0/standalone/deployments/RESTfulExample.war/WEB-INF/lib/jaxb-impl-2.2.3-1.jar does not point to a valid jar for a Class-Path reference.
    11:25:15,512 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015960: Class Path entry activation.jar in /C:/Program Files/EAP-6.0.1/jboss-eap-6.0/standalone/deployments/RESTfulExample.war/WEB-INF/lib/jaxb-impl-2.2.3-1.jar does not point to a valid jar for a Class-Path reference.
    11:25:15,512 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015960: Class Path entry jsr173_1.0_api.jar in /C:/Program Files/EAP-6.0.1/jboss-eap-6.0/standalone/deployments/RESTfulExample.war/WEB-INF/lib/jaxb-impl-2.2.3-1.jar does not point to a valid jar for a Class-Path reference.
    11:25:15,513 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015960: Class Path entry jaxb1-impl.jar in /C:/Program Files/EAP-6.0.1/jboss-eap-6.0/standalone/deployments/RESTfulExample.war/WEB-INF/lib/jaxb-impl-2.2.3-1.jar does not point to a valid jar for a Class-Path reference.
    11:25:15,523 WARN [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015893: Encountered invalid class name ‘com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App’ for service type ‘javax.ws.rs.ext.MessageBodyReader’
    .
    .
    and the RESTfulExample does not deploy. Any ideas?

    Reply
  24. Hi, Just wondering how to send a object to a get request?. I need to send a list of many filter parameters which the user selects from UI and get the data back in Response. I can now retrieve data by passing the object in post request but this is wrong way of doing things as what the code actually does is a GET to the server which will retrieve data passing in the list.

    Reply
  25. The tutorial may be simple but its defenitely wrong. How can you say it is RESTful when you use something like @Path(“/post”). This is clearly RPC-Hybrid. You still thinking in methods not in resources.

    Suggestion: @Path(“/album”).
    Please do not post stuff randomly on your blog. (not the first time)

    Reply
  26. can you provide code which works for HTTPS url, ie for SSL connection.

    Reply
  27. when i try to call post method it gives the error java.lang.RuntimeException: Failed : HTTP error code : 500.
    Get method is properly works.

    Reply
  28. Thanks for the wonderful tutorial, Can we have https example like same

    Reply
  29. Hi Mkyong,

    how do I assign the data received from service to a data structure on client side, e.g., XML and JSON data into a List of entity class? Will you please give some sample code?

    Thanks in advance.

    Reply
  30. Thank you for your wonderful tutorial.

    in POST Request, the status check should be for 200 , 201 was not working for me.

    if (response.getStatus() != 201) {
    ———–
    }

    should be
    if (response.getStatus() != 200) {
    ———–
    }

    Reply
  31. please help me out with this error
    Http status 404

    Reply
    1. Hi Neha,

      Did you get any solution ?

      I am also facing the same problem.

      When I am hitting the browser with URL : “http://localhost:8080/RESTfulExample/rest/json/metallica/get” I am getting a proper result

      ————————————————————-
      {“title”:”Enter Sandman”,”singer”:”Metallica”}
      ————————————————————–

      But when I am trying to run the client code ‘/RESTfulExample1/src/main/java/com/mkyong/client/JerseyClientGet.java’

      I am getting the error

      =============================================================================

      java.lang.RuntimeException: Failed : HTTP error code : 404
      at com.mkyong.client.JerseyClientGet.main(JerseyClientGet.java:24)
      ===============================================================================

      anybody please guide me to get a solution its really getting frustrating.

      Reply
      1. Hi,

        using the “http://localhost:8080/RESTfulExample/rest/json/metallica/get” url

        i am facing the following error

        com.sun.jersey.spi.container.ContainerResponse write

        SEVERE: A message body writer for Java class com.mkyong.Track, and Java type class com.mkyong.Track, and MIME media type application/json was not found

        18 Mar, 2014 2:52:58 PM com.sun.jersey.spi.container.ContainerResponse write

        SEVERE: The registered message body writers compatible with the MIME media type are:

        */* ->

        com.sun.jersey.core.impl.provider.entity.FormProvider

        com.sun.jersey.core.impl.provider.entity.StringProvider

        com.sun.jersey.core.impl.provider.entity.ByteArrayProvider

        com.sun.jersey.core.impl.provider.entity.FileProvider

        com.sun.jersey.core.impl.provider.entity.InputStreamProvider

        com.sun.jersey.core.impl.provider.entity.DataSourceProvider

        com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General

        com.sun.jersey.core.impl.provider.entity.ReaderProvider

        com.sun.jersey.core.impl.provider.entity.DocumentProvider

        com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider

        com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter

        com.sun.jersey.server.impl.template.ViewableMessageBodyWriter

        com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General

        com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General

        18 Mar, 2014 2:52:58 PM com.sun.jersey.spi.container.ContainerResponse logException

        SEVERE: Mapped exception to response: 500 (Internal Server Error)

        javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.mkyong.Track, and Java type class com.mkyong.Track, and MIME media type application/json was not found

        at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)

        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1479)

        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)

        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)

        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)

        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537)

        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699)

        at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

        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:233)

        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)

        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)

        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)

        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)

        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)

        at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)

        at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)

        at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)

        at java.lang.Thread.run(Unknown Source)

        Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.mkyong.Track, and Java type class com.mkyong.Track, and MIME media type application/json was not found

        … 20 more

        Reply
    2. If running on eclipse , make sure that your project is loaded on the server and the server is turned on .

      Reply
  32. I have tried alot…followed all the steps given but my hello world rest api is not running and giving an error Http status 404.
    dont know whats wrong in it.
    any help or suggestion is appreciated.
    Thanks in advance.

    Reply
  33. Your articles are very simple and extremely helpful.

    I thin you need to make slight change in the pom.xml as it fails if we run as it is.

    The version of jersey-server needs to be 1.18.

    com.sun.jersey
    jersey-server
    1.15

    That would mean changes to the .classpath file of the project

    Reply
  34. This tutuorial was excellent and simple. It would be handy if you showed how to add arguments to the GET example. I tested by building my arguments into the webresource statement but I think there is a way to create queryParams before calling the webresource. Having trouble figuring this out at the moment.

    Reply
  35. Hi Thanks for the above example , I is working for me as expected could you please share how to display that JSON in jsp page

    Reply
  36. Hi,
    Excellent tutorial and I got great help from it. Just a small note from my side. I did everthing as you said(well almost) but still got the following from message from my server

    “Saved in Serverorg.ird.rest.model.Form@fb6763” when it should have returned JSON string. I removed the ‘result’ String object and directly added the object of the Class I recieved

    return Response.status(201).entity(result).build();
    to
    return Response.status(201).entity(form).build();

    to get:
    {“formName”:”Follow-up”,”description”:”This is sent from client”}

    which resulted in the expected JSON string being returned from server. Don’t know why concatenating a string message with the object cause this behaviour.

    Reply
  37. How do i pass a list in a json through using the above client.Sample Json should look like this:
    {
    “age”:100,
    “name”:”mkyong.com”,
    “messages”:[“msg 1″,”msg 2″,”msg 3”]
    }

    Reply
    1. import org.codehaus.jettison.json.JSONObject

      Map input = new HashMap();
      input.put(“age”, “100”);
      input.put(“name”, “mkyong.com”);
      //not too sure about a list in a map, but try it out using same principle

      JSONObject jsonList = new JSONObject(input);

      ClientResponse response = webResource.type(“application/json”)
      .post(ClientResponse.class, jsonList);

      Reply
  38. Hi,
    How can I create a POST call by using the POSTMAN or FIDDLER tools?

    Reply
  39. Thanks, your tutorials have helped me many times. I’m looking around for some guidance and can’t seem to find anything covering my question.

    I have a rest (Wink) service that @produces(“application/zip”), via below code. This works fine from the browser but I am writing a Wink Rest client to get the file and I would like to get the file from the Response.getEntity() so I can save it to disk and evaluate it, test it, etc. Maybe what I need is a FileProvider but I’m not sure if that’s the right direction.

    I’d appreciate any guidance you could give me. Thanks!

        ResponseBuilder responseBuilder = null;
        javax.ws.rs.core.Response response = null;
        InputStream in = null;
        try {
          
          in = new FileInputStream( createZipFile( filesToZip ) );
          responseBuilder = javax.ws.rs.core.Response.ok(in, MediaType.APPLICATION_OCTET_STREAM_TYPE);
          response = responseBuilder.header("content-disposition", "inline;filename="file.zip").build();
    
        } catch( FileNotFoundException fnfe) {
              fnfe.printStackTrace();
        }
        
        return response;
    
    Reply
  40. How can I have the JSON recieved on client side converted to Track object.
    In SOAP based services, you had tools that provide stub/skeleton classes to convert to java objects on client side. Is something similar possible here

    Reply
  41. Too many times have I looked and learned from at your posts and not thanked you for it.
    So here I am for all those times -THANK YOU, THANK YOU, THANK YOU! 😉

    You always manage to keep it simple and to-the-point, and its easy to understand at first glance.
    Great work and keep it up man.
    Cheers!

    Reply
  42. These JSON/Jersey/Spring articles have been extremely helpful for me. Thank you for putting them togheter. Very easy to read and with some very good examples which I have shamelessy borrowed. 😛

    Reply
  43. This example is not working in Amazon’s Elastic Beanstalk
    I could able to get it worked in localhost.
    Any idea how I can see logs or proceed further?

    Reply
  44. I have done same thing but at the time getting values in String i got the following error please help me..
    {“error”:{“code”:400,”message”:”Unable to complete operation.”,”details”:[“Invalid Token”]}}

    Reply
  45. If I just want to post a JSONObject (org.json.JSONObject or net.sf.json.JSONObject), what I should do?

    Reply
  46. why get and post are used as part of the url, it seems to me like REST url smell.

    Reply
  47. I have spent nearly 20 hours to get “JSONP” to work with Jersey to overcome the cross-domain issue.
    Passing on…

    Here is the JavaScript client side:

    $.getJSON("http://localhost:8080/rest/json/metallica/get?callback=?",
    	{},
    	function(data) {
    		$("#status2").html( "<h2>" + data.singer + " " + data.title + "<h2>");
    	}
    );
    

    Here is the Java Server side
    The trick is to match the callback parameter name (callback in this case) and to return a JSONWithPadding Object
    The server side should be improved to return a collection instead of a simple Track object

    package com.pacsman.jersey;
    
    import javax.ws.rs.Consumes;
    import javax.ws.rs.DefaultValue;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.QueryParam;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    import com.mkyong.Track;
    import com.sun.jersey.api.json.JSONWithPadding;
    
    @Path("/json/metallica")
    public class JSONService {
    
    	@GET
    	@Path("/get")
    	@Produces("application/x-javascript")
    	public JSONWithPadding getTrackInJSON(
    			@QueryParam("callback") @DefaultValue("CBParamIsMissing") String jsoncallback) {
    		Track track = new Track();
    		track.setTitle("Enter Sandman");
    		track.setSinger("Metallica3");
    
    		return new JSONWithPadding(track, jsoncallback);
    	}
    }
    
    Reply
  48. hi thx for the sample this is a good example for basic understanding..

    there is a small problem in sample we need to add @XmlRootElement in Track.call to make this work

    import javax.xml.bind.annotation.XmlRootElement;
    @XmlRootElement
    public class Track {

    Reply
  49. for example a’ve method in service like this

    @POST
    @Path(“/login”)
    @Consumes(MediaType.APPLICATION_JSON)
    public Response checkUser(String username, String password) {
    ………………….
    }

    How can i send multiple parameter from client. Thank you..

    Reply
  50. Thanks a lot for such easy and complete tutorial.
    Simplicity makes it easy to understand.

    Reply
  51. Thanks for this great tutorial. Very much appreciated.

    Lan

    Reply
    1. This tutuorial was excellent and simple. It would be handy if you showed how to add arguments to the GET example. I tested by building my arguments into the webresource statement but I think there is a way to create queryParams before calling the webresource. Having trouble figuring this out at the moment.

      Reply
      1. Hi Mykong,

        Thanks for this useful website

        But when i run this main class as a JAVA application, I m getting only the below o/p
        from the

        input is:{“singer”:”Metallica”,”title”:”Fade To Black”}
        The response is: 415
        Output from Server ….

        Reply
        1. I mean its not hitting my webservice JSONService and doesn’t give me the o/p

          Track saved : Track [title=Fade To Black, singer=Metallica]

          Reply
          1. really a simple and great resource.

          1. Hi All,

            Use the below additional dependency for the jersey-json.This will fix the issue.

            com.sun.jersey
            jersey-server
            1.8

Leave a Comment

Your email address will not be published. Required fields are marked *