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)
Thanks for the wonderful tutorial, Can we have https example like same
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?
Please , how about ssl url
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
====================
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 “.
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!
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!
Thank you! Great and simple tutorial
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.
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
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…?
can you give me the solution..?
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?
how to use Restful with struts 1.3
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!
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
How to parse the output to get only specific values alone from the response.i.e get only singer attribute.
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;
I this above exception how could i add timeOut to server
Really a nice example to understand the get and post difference in client and server . Thank u so much .
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.
Nice tool for json htto://jsonformatter.org
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
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
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.
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
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?
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.
Hi,
I do:
ClientResponse response = webResource.type(“application/json”).accept(“application/json”).post(ClientResponse.class, input);
Is correct?
What if a webservice consumes and produces JSON object?
hi
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?