Recently I have to pass JSON data to REST Service and did not have any simple Client handy. But created very simple Java program which read JSON data from file and sends it to REST service.
Representational State Transfer (REST) has gained widespread acceptance across the Web as a simpler alternative to SOAP- and Web Services Description Language (WSDL)-based Web services. Key evidence of this shift in interface design is the adoption of REST by mainstream Web 2.0 service providers—including Yahoo, Google, and Facebook—who have deprecated or passed on SOAP and WSDL-based interfaces in favor of an easier-to-use, resource-oriented model to expose their services. In this article, Alex Rodriguez introduces you to the basic principles of REST.
Let’s start coding this:
- Create RESTFul Web Service
- Java file: CrunchifyRESTService.java
- web.xml file
- Create RESTService Client
- CrunchifyRESTServiceClient.java file
Another must read: Spring MVC Example/Tutorial: Hello World – Spring MVC 3.2.1
Step-1
In Eclipse => File => New => Dynamic Web Project
. Name it as “CrunchifyTutorials
”. Below tutorial also works with Tomcat 8
.
Step-2 Create Deployment Descriptor File
If you don’t see web.xml
(deployment descriptor) under WebContent\WEB-INF\
then follow these steps.
Open web.xml
and replace content with below contents:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>CrunchifyRESTJerseyExample</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> </web-app>
Step-3 Convert Project to Maven Project
Follow this tutorial: https://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/. Here is my pom.xml file.
<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>CrunchifyTutorials</groupId> <artifactId>CrunchifyTutorials</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>asm</groupId> <artifactId>asm-all</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-bundle</artifactId> <version>1.14</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> </dependencies> </project>
Step-4
Create RESTFul service: CrunchifyRESTService.java
. Here we will create two services:
/api/crunchifyService
– POST call – we will use this with our test/api/verify
– GET call – just to make sure service started successfully
package com.crunchify.tutorials; /** * @author Crunchify.com * */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.print.attribute.standard.Media; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/") public class CrunchifyRESTService { @POST @Path("/crunchifyService") @Consumes(MediaType.APPLICATION_JSON) public Response crunchifyREST(InputStream incomingData) { StringBuilder crunchifyBuilder = new StringBuilder(); try { BufferedReader in = new BufferedReader(new InputStreamReader(incomingData)); String line = null; while ((line = in.readLine()) != null) { crunchifyBuilder.append(line); } } catch (Exception e) { System.out.println("Error Parsing: - "); } System.out.println("Data Received: " + crunchifyBuilder.toString()); // return HTTP response 200 in case of success return Response.status(200).entity(crunchifyBuilder.toString()).build(); } @GET @Path("/verify") @Produces(MediaType.TEXT_PLAIN) public Response verifyRESTService(InputStream incomingData) { String result = "CrunchifyRESTService Successfully started.."; // return HTTP response 200 in case of success return Response.status(200).entity(result).build(); } }
Step-5
Deploy project CrunchifyTutorials
on Tomcat. Web project should be deployed without any exception.
- Right Click on
Servers tab
in Eclipse - Click on
Add and Remove...
Project - Add Project CrunchifyTutorials to right
Configured:
side. - Click on
Publish
- Click on
Start
Step-6 Verify REST service
Rest service should be accessible using this URL: http://127.0.0.1:8080/CrunchifyTutorials/api/verify
If you try to access http://127.0.0.1:8080/CrunchifyTutorials/api/crunchifyService then you will see error code 405 - Method not allowed
– which is valid response. As you can see it’s POST call and should expect some data with the request.
Let’s move on.
Step-7
Copy below JSON content and put it under C:\\CrunchifyJSON.txt
file for windows or /Users/<username>/Documents/CrunchifyJSON.txt
file if Macbook.
{ "tutorials": { "id": "Crunchify", "topic": "REST Service", "description": "This is REST Service Example by Crunchify." } }
Step-8
Create REST Call Client: CrunchifyRESTServiceClient.java.
Please change path to CrunchifyJSON.txt
in below program.
package com.crunchify.tutorials; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import org.json.JSONObject; /** * @author Crunchify.com * */ public class CrunchifyRESTServiceClient { public static void main(String[] args) { String string = ""; try { // Step1: Let's 1st read file from fileSystem // Change CrunchifyJSON.txt path here InputStream crunchifyInputStream = new FileInputStream("/Users/<username>/Documents/CrunchifyJSON.txt"); InputStreamReader crunchifyReader = new InputStreamReader(crunchifyInputStream); BufferedReader br = new BufferedReader(crunchifyReader); String line; while ((line = br.readLine()) != null) { string += line + "\n"; } JSONObject jsonObject = new JSONObject(string); System.out.println(jsonObject); // Step2: Now pass JSON File Data to REST Service try { URL url = new URL("http://localhost:8080/CrunchifyTutorials/api/crunchifyService"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while (in.readLine() != null) { } System.out.println("\nCrunchify REST Service Invoked Successfully.."); in.close(); } catch (Exception e) { System.out.println("\nError while calling Crunchify REST Service"); System.out.println(e); } br.close(); } catch (Exception e) { e.printStackTrace(); } } }
Step-9
Now let’s run Client Program by right click on CrunchifyRESTServiceClient.java and you should see below two outputs
1) in Tomcat Console
2) in Local Client Console