How To Get Json Object From Restful Web Service
Recently I have to laissez passer JSON data to REST Service and did not have any simple Customer handy. But created very unproblematic Coffee program which read JSON information from file and sends it to Balance service.
Representational Land Transfer (Rest) has gained widespread acceptance across the Web every bit a simpler alternative to Soap- and Web Services Clarification Language (WSDL)-based Spider web services. Key prove of this shift in interface design is the adoption of Residue by mainstream Web 2.0 service providers—including Yahoo, Google, and Facebook—who have deprecated or passed on Lather 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 bones principles of REST.
Let's beginning coding this:
- Create RESTFul Web Service
- Java file: CrunchifyRESTService.coffee
- web.xml file
- Create RESTService Customer
- CrunchifyRESTServiceClient.java file
Another must read: Leap MVC Instance/Tutorial: How-do-you-do World – Spring MVC 3.2.1
Step-1
In Eclipse => File => New => Dynamic Web Projection
. Name it as "CrunchifyTutorials
". Beneath tutorial also works with Tomcat eight
.
Step-2 Create Deployment Descriptor File
If yous don't run across spider web.xml
(deployment descriptor) under WebContent\WEB-INF\
and so follow these steps.
Open spider web.xml
and supplant content with below contents:
1 ii three iv 5 half dozen 7 8 9 ten 11 12 13 xiv xv 16 17 18 nineteen xx 21 22 23 24 25 | <? xml version="one.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.dominicus.com/xml/ns/javaee http://java.lord's day.com/xml/ns/javaee/web-app_3_0.xsd" version="three.0" > < display-name > CrunchifyRESTJerseyExample </brandish-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-listing > < servlet > < servlet-name > Jersey Web Application </servlet-name > < servlet-class > com . dominicus . jersey . spi . container . servlet . ServletContainer </servlet-class > < load-on-startup > 1 </load-on-startup > </servlet > < servlet-mapping > < servlet-name > Jersey Web Application </servlet-proper name > < url-pattern >/api/*</url-design > </servlet-mapping > </web-app > |
Footstep-3 Convert Project to Maven Project
Follow this tutorial: https://crunchify.com/how-to-convert-existing-java-projection-to-maven-in-eclipse/. Here is my pom.xml file.
1 ii iii 4 5 half-dozen 7 8 9 x eleven 12 13 14 15 16 17 18 nineteen 20 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | < projection 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-four.0.0.xsd" > < modelVersion > 4.0.0 </modelVersion > < groupId > CrunchifyTutorials </groupId > < artifactId > CrunchifyTutorials </artifactId > < version > 0.0.1-SNAPSHOT </version > < packaging > state of war </packaging > < build > < sourceDirectory > src </sourceDirectory > < plugins > < plugin > < artifactId > maven-compiler-plugin </artifactId > < version > 3.1 </version > < configuration > < source > 1.viii </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 > three.iii.1 </version > </dependency > < dependency > < groupId > com . lord's day . jersey </groupId > < artifactId > jersey-bundle </artifactId > < version > ane.14 </version > </dependency > < dependency > < groupId > org . json </groupId > < artifactId > json </artifactId > < version > 20090211 </version > </dependency > </dependencies > </project > |
Footstep-4
Create RESTFul service: CrunchifyRESTService.java
. Here we will create two services:
-
/api/crunchifyService
– POST call – we volition use this with our test -
/api/verify
– Become telephone call – just to make sure service started successfully
1 2 three 4 5 6 vii 8 9 10 eleven 12 13 14 15 sixteen 17 18 nineteen 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package com . crunchify . tutorials ; /** * @author Crunchify.com * */ import java . io . BufferedReader ; import java . io . InputStream ; import coffee . io . InputStreamReader ; import javax . impress . 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 course CrunchifyRESTService { @POST @Path ( "/crunchifyService" ) @Consumes ( MediaType . APPLICATION_JSON ) public Response crunchifyREST ( InputStream incomingData ) { StringBuilder crunchifyBuilder = new StringBuilder ( ) ; endeavor { BufferedReader in = new BufferedReader ( new InputStreamReader ( incomingData ) ) ; String line = zilch ; while ( ( line = in . readLine ( ) ) != null ) { crunchifyBuilder . suspend ( line ) ; } } catch ( Exception e ) { Arrangement . out . println ( "Error Parsing: - " ) ; } System . out . println ( "Information Received: " + crunchifyBuilder . toString ( ) ) ; // return HTTP response 200 in instance of success return Response . status ( 200 ) . entity ( crunchifyBuilder . toString ( ) ) . build ( ) ; } @Get @Path ( "/verify" ) @Produces ( MediaType . TEXT_PLAIN ) public Response verifyRESTService ( InputStream incomingData ) { String event = "CrunchifyRESTService Successfully started.." ; // render HTTP response 200 in case of success render Response . status ( 200 ) . entity ( effect ) . build ( ) ; } } |
Step-v
Deploy project CrunchifyTutorials
on Tomcat. Web projection should exist deployed without any exception.
- Correct Click on
Servers tab
in Eclipse - Click on
Add together and Remove...
Projection - Add together Project CrunchifyTutorials to right
Configured:
side. - Click on
Publish
- Click on
Get-go
Step-6 Verify REST service
Residuum service should be attainable using this URL: http://127.0.0.i:8080/CrunchifyTutorials/api/verify
If you try to access http://127.0.0.1:8080/CrunchifyTutorials/api/crunchifyService then you lot will see mistake code 405 - Method not immune
– which is valid response. Every bit you lot tin can see it's POST phone call and should await some data with the request.
Permit's movement on.
Stride-7
Re-create beneath 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 Case by Crunchify." } } |
Footstep-8
Create REST Call Client: CrunchifyRESTServiceClient.java.
Please modify path to CrunchifyJSON.txt
in below plan.
1 2 iii 4 5 6 7 eight ix 10 11 12 13 14 xv 16 17 18 19 twenty 21 22 23 24 25 26 27 28 29 xxx 31 32 33 34 35 36 37 38 39 xl 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | bundle com . crunchify . tutorials ; import java . io . BufferedReader ; import java . io . FileInputStream ; import coffee . 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 ) { Cord string = "" ; try { // Step1: Let'due south 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 ) ; Organisation . out . println ( jsonObject ) ; // Step2: Now laissez passer JSON File Information to REST Service attempt { URL url = new URL ( "http://localhost:8080/CrunchifyTutorials/api/crunchifyService" ) ; URLConnection connection = url . openConnection ( ) ; connection . setDoOutput ( true ) ; connexion . setRequestProperty ( "Content-Blazon" , "application/json" ) ; connection . setConnectTimeout ( 5000 ) ; connectedness . setReadTimeout ( 5000 ) ; OutputStreamWriter out = new OutputStreamWriter ( connectedness . getOutputStream ( ) ) ; out . write ( jsonObject . toString ( ) ) ; out . close ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( connectedness . getInputStream ( ) ) ) ; while ( in . readLine ( ) != zippo ) { } System . out . println ( "\nCrunchify Residue Service Invoked Successfully.." ) ; in . close ( ) ; } catch ( Exception e ) { System . out . println ( "\nError while calling Crunchify REST Service" ) ; System . out . println ( due east ) ; } br . close ( ) ; } grab ( Exception e ) { e . printStackTrace ( ) ; } } } |
Step-9
Now let's run Client Plan by right click on CrunchifyRESTServiceClient.java and y'all should encounter below two outputs
i) in Tomcat Console
two) in Local Customer Console
Source: https://crunchify.com/create-very-simple-jersey-rest-service-and-send-json-data-from-java-client/
Posted by: mcphersonaughteell.blogspot.com
0 Response to "How To Get Json Object From Restful Web Service"
Post a Comment