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
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: laan penge nu()

  • Pingback: car parking()

  • Pingback: water ionizer()

  • Pingback: laan penge her og nu()

  • Pingback: lan penge nu sms()

  • Pingback: mp4 mobile porn()

  • Pingback: here()

  • Pingback: Business DIRECTV()

  • Pingback: online casinos()

  • Pingback: unblock vider()

  • Pingback: enagic kangen water()

  • Pingback: kangen water machine()

  • Pingback: alkaline water()

  • Pingback: water ionizers()

  • Pingback: tv online, online tv()

  • Pingback: stream movies()

  • Pingback: Blue Coaster33()

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • Orrimp

    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)

  • yogesh prajapati

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

  • Daniel

    Thank you! Great and simple tutorial

  • nisa

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

  • Nikhil

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

  • [email protected]

    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.

  • Vinay Kumar

    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) {
    ———–
    }

  • neha

    please help me out with this error
    Http status 404

    • Sushil

      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.

    • Shashank Awasthi

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

  • neha

    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.

  • Ajay

    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

  • Zeus

    why metallica? :)

  • http://www.telecomcto.com Leo P

    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.

  • Ravi

    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

  • http://omarnama.blogspot.com Omar

    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.

  • kumar

    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″]
    }

  • maybe

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

  • Kevin

    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(&quot;content-disposition&quot;, &quot;inline;filename=&quot;file.zip&quot;).build();
     
        } catch( FileNotFoundException fnfe) {
              fnfe.printStackTrace();
        }
     
        return response;
  • chandar

    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

  • Rajeev

    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!

  • Richard

    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. :-P

  • Deepak

    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?

  • Nitin

    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”]}}

  • Santosh

    thansk for this simple example. which helped me a lot.

  • max

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

  • thegreatdao

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

    • test

      They don’t have to be used as a part of the url.

  • Pingback: Cloud integration and DevOps automation experience shared | horovits()

  • Christophe

    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(&quot;http://localhost:8080/rest/json/metallica/get?callback=?&quot;,
    	{},
    	function(data) {
    		$(&quot;#status2&quot;).html( &quot;&lt;h2&gt;&quot; + data.singer + &quot; &quot; + data.title + &quot;&lt;h2&gt;&quot;);
    	}
    );

    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(&quot;/json/metallica&quot;)
    public class JSONService {
     
    	@GET
    	@Path(&quot;/get&quot;)
    	@Produces(&quot;application/x-javascript&quot;)
    	public JSONWithPadding getTrackInJSON(
    			@QueryParam(&quot;callback&quot;) @DefaultValue(&quot;CBParamIsMissing&quot;) String jsoncallback) {
    		Track track = new Track();
    		track.setTitle(&quot;Enter Sandman&quot;);
    		track.setSinger(&quot;Metallica3&quot;);
     
    		return new JSONWithPadding(track, jsoncallback);
    	}
    }
    • Ashwin

      Thanks a log for this tutorial.

  • haris

    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 {

    • Joseph

      No you dont unless you want to use jaxb

  • Siregar

    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..

  • Ketan

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

  • Lan Ledin

    Thanks for this great tutorial. Very much appreciated.

    Lan

    • http://www.telecomcto.com Leo P

      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.

      • priyalakshmi

        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 ….

        • priyalakshmi

          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]