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
- JSON example with Jersey + Jackson
- Jersey client examples
- RESTful Java client with RESTEasy client framework
- RESTful Java client with java.net.URL
- RESTful Java client with Apache HttpClient

why metallica? :)
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.
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
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.
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"]
}
Hi,
How can I create a POST call by using the POSTMAN or FIDDLER tools?
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!
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
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!
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
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?
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"]}}
thansk for this simple example. which helped me a lot.
If I just want to post a JSONObject (org.json.JSONObject or net.sf.json.JSONObject), what I should do?
why get and post are used as part of the url, it seems to me like REST url smell.
They don’t have to be used as a part of the url.
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:
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
Thanks a log for this tutorial.
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 {
No you dont unless you want to use jaxb
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..
Thanks a lot for such easy and complete tutorial.
Simplicity makes it easy to understand.
Thanks for this great tutorial. Very much appreciated.
Lan
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.