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
”
Step 2) If you don’t see web.xml
(deployment descriptor) under WebContent\WEB-INF\
then follow these steps.
Step 3) Open Web.xml and replace content with below contents:
<?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/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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 4: Create RESTFul service
package com.crunchify.tutorials; /** * @author Crunchify.com * */ import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; 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(); } }
Step 5: You may need to download these 3 files: asm-3.3.1.jar
, jersey-bundle-1.14.jar
, json.jar
Step 6: Deploy project CrunchifyTutorials
on Tomcat. Web project should be deployed without any exception.
Step 7 : Rest service should be accessible using this URL: http://localhost:8080/CrunchifyTutorials/api/crunchifyService
Step 8: Create REST Call Client.
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 InputStream crunchifyInputStream = new FileInputStream( "/Users/<username>/Documents/crunchify-git/JSONFile.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("\nREST Service Invoked Successfully.."); in.close(); } catch (Exception e) { System.out.println("\nError while calling REST Service"); System.out.println(e); } br.close(); } catch (Exception e) { e.printStackTrace(); } } }
Step 9: Now let’s run Client Program and you should see output in Tomcat Console and Local Client Console.
The post Create Very Simple Jersey REST Service and Send JSON Data From Java Client appeared first on Crunchify.
Author: Arpit Shah.