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

About the Author

author image
mkyong
Founder of Mkyong.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

Leave a Reply

avatar
newest oldest most voted
Vivek Agrawal
Guest
Vivek Agrawal

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.

aden2015
Guest
aden2015

Please , how about ssl url

realomok
Guest
realomok

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

Nikhil
Guest
Nikhil

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

Gino
Guest
Gino

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?

AJC
Guest
AJC

What if a webservice consumes and produces JSON object?

Leo P
Guest
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.

Kumar
Guest
Kumar

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

kamlesh dave
Guest
kamlesh dave

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

Dnyaneshwar
Guest
Dnyaneshwar
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… Read more »
Dnyaneshwar
Guest
Dnyaneshwar

I this above exception how could i add timeOut to server

Joy
Guest
Joy

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

Iris Panabaker
Guest
Iris Panabaker

Nice tool for json htto://jsonformatter.org

sumi catty
Guest
sumi catty

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

Guest
Guest
Guest

example Source Thanks
Now, jersey dependency Group Id Moved

org.glassfish.jersey.core

jersey-server

1.8

com.sun.jersey

jersey-json

1.8

org.glassfish.jersey.core

jersey-client

1.8

Link: http://mvnrepository.com/artifact/com.sun.jersey/jersey-server

Gunachandra Hijam
Guest
Gunachandra Hijam

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.

Bikash Singh
Guest
Bikash Singh

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

latte
Guest
latte

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?

dhananjai singh
Guest
dhananjai singh

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.

Victor
Guest
Victor

Hi,

I do:

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

Is correct?

Victor
Guest
Victor

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!

hi
Guest
hi

hi

Hung Trinh
Guest
Hung Trinh

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?

Freeman Stokes
Guest
Freeman Stokes

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!

EFHAJG0
Guest
EFHAJG0
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… Read more »
kary
Guest
kary

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.

trackback
JAX-RS TUTORIALS | BUYWORKSELL

[…] RESTful Java client with Jersey client […]

Orrimp
Guest
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
Guest
yogesh prajapati

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

Daniel
Guest
Daniel

Thank you! Great and simple tutorial

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