Newsletter |
RESTful Java Client Example Using Jersey Client
Web Services » on Aug 5, 2014 { 11 Comments } By Sivateja
In this article i will describe how to write a JAX-RS client application using jersey client API, so far we used to call & test/read our RESTful service by its URL directly hitting in the browser [ check the previous examples ], but in the real time we will call the services by writing some client application logic. We have different ways to write a RESTful client. In this article i will use Jersey client [ of course we are using Jersey for writing RESTful service too 🙂 ]
Steps need to be followed
- Need to add ‘jersey-client‘ dependency in pom.xml
- As we are creating the Client application, we need to write a RESTful service to test that client, so i will take previous JSON example in order to do that
- Write a client application and run it 🙂
Files Required
- pom.xml
- web.xml
- JsonFromRestful.java
- Customer.java
- RESTfulClient.java
pom.xml
In the pom.xml we must include ‘jersey-client’ dependency [ Check line numbers from 4-10 ]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JAX-RS-Client-Example</groupId> <artifactId>JAX-RS-Client-Example</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <repositories> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </repository> </repositories> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.8</version> </dependency> </dependencies> <build> <finalName>JAX-RS-Client-Example</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerVersion>1.5</compilerVersion> <source>1.5</source> <target>1.5</target> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4"> <display-name>JAX-RS-Client-Example</display-name> <servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>java4s</param-value> </init-param> <init-param> <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
JsonFromRestful.java
package java4s; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; @Path("/customers") public class JsonFromRestful { @GET @Path("/{cusNo}") @Produces("application/json") public Customer produceCustomerDetailsinJSON(@PathParam("cusNo") int no) { /* * I AM PASSING CUST.NO AS AN INPUT, SO WRITE SOME BACKEND RELATED STUFF AND * FIND THE CUSTOMER DETAILS WITH THAT ID. AND FINALLY SET THOSE RETRIEVED VALUES TO * THE CUSTOMER OBJECT AND RETURN IT, HOWEVER IT WILL RETURN IN JSON FORMAT :-) * */ Customer cust = new Customer(); cust .setCustNo(no); cust .setCustName("Java4s"); cust .setCustCountry("India"); return cust; } }
Customer.java
package java4s; public class Customer { private int custNo; private String custName; private String custCountry; public int getCustNo() { return custNo; } public void setCustNo(int custNo) { this.custNo = custNo; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustCountry() { return custCountry; } public void setCustCountry(String custCountry) { this.custCountry = custCountry; } }
RESTfulClient.java
package java4s; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; public class RESTfulClient { public static void main(String[] Java4s) { try { Client client = Client.create(); WebResource resource = client.resource("http://localhost:2015/JAX-RS-Client-Example/rest/customers/100"); ClientResponse response = resource.accept("application/json").get(ClientResponse.class); if(response.getStatus() == 200){ String output = response.getEntity(String.class); System.out.println(output); }else System.out.println("Somthing went wrong..!"); } catch (Exception e) { e.printStackTrace(); } } }
Explanation:
- Line number 13, we are calling our rest service
- Line number 14, we are intimating the REST Service that our client will accept JSON response
- Right click on RESTfulClient.java in eclipse > Run As > Run on Server
You Might Also Like
::. About the Author .:: | ||
Comments
11 Responses to “RESTful Java Client Example Using Jersey Client”
Hi Sir,
I am using Struts2+Spring combination.
I want to retrieve data from database and display data in drop down box (select tag). used queryForList(“……”) in spring. but I am getting drop down like this{{key=1},{value=India}} format. How can I solve this problem? can you send me any example. I want to display “India” and key is “1”.
Thanks & Regards,
Jagannath Kale
Hi,
I could not understand, why you have used RESTfulClient.java.
Please explain.
Thanks in advance
1] We can call web-service from Jsp as well as from java class; is there any particular difference between them? Which one is better in production environment
2] How is Rest web-service called in production or Live projects? What coding is required to call it in production environment.
Hi Sir,
When I run the client: RESTfulClient.java, it gives me Http status 404 error. Where am I going wrong.
Difference between Soap and Rest ? Why rest is better then to soap?
soap is dependent on wsdl.in the case of rest dependent on uri.soap is accept only xml format,rest allows josn,xml,text etc….learning soap is diffcult rest very esasy to learn.
I am getting HTTP Status 404-
Hi sir first of all very thanks for such an ultimate tutorial.
please give soap examples also.
@Purva @venkatesh
I also got the same problem.I got the solution for this.There could be three reasons as mentioned below
————————————————————————————————–
1. First deploy r application on the tomcat server.to do this run as on server
2. run your RestfulClient.java file as "JavaApplication" and do not run this file on server.This file is
designed to get data from a rest api is deployed on your tomcat server
you will be able to see your output in console.
—————————-
Another reson could be give proper package name in your web.xml at line in param value.give your package name which you have created, do not copy paste as it is.
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>java4s</param-value>
</init-param>
——————————–
Third reason could be that url in RestClient file
here it is mentioned as
http://localhost:2015/JAX-RS-Client-Example/rest/customers/100
be careful to give correct port no on which your current server is running.
IN my case it is 8080 so I changed url to
http://localhost:8080/JAX-RS-Client-Example/rest/customers/100
in my RestClint.java file
I used your tutorial as a first step of restful. its really very helpful to understand basic steps and concept.
Really Thanks for your honest Guidance.
M.Parmar
RESTful POST method "Client-side coding should be in Java " with payload-data(user,pass)this is send as JSON to Server.Server sends back log-in Message in JSON format
JSON Data send by Client Looks like this
{
"usr":"shoaibshaikh1516@gmail.com",
"pwd":"qweqwe"
}
My code looks like this real data:
URL url = new URL("https://greenpyramid.erpnext.com/api/method/login");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"usr\": \"shoaibshaikh1516@gmail.com\", \"pwd\": \"qweqwe\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server …. \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I am getting 401 error