Preface
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:
1. Create RESTFul Web Service
2. Create RESTService Client
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 “DemoWS”. 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:
Step-3 Convert Project to Maven Project
Follow this tutorial: http://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/. Below is my pom.xml:
Step-4
Create RESTFul service: DemoRESTService.java. Here we will create two services:
- package com.demo.tutorials;
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- 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 DemoRESTService {
- @POST
- @Path("/demoService")
- @Consumes(MediaType.APPLICATION_JSON)
- public Response crunchifyREST(InputStream incomingData) {
- StringBuilder strBuilder = new StringBuilder();
- try {
- BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
- String line = null;
- while ((line = in.readLine()) != null) {
- strBuilder.append(line);
- }
- } catch (Exception e) {
- System.out.println("Error Parsing: - ");
- }
- System.out.println("Data Received: " + strBuilder.toString());
- // return HTTP response 200 in case of success
- return Response.status(200).entity(strBuilder.toString()).build();
- }
- @GET
- @Path("/verify")
- @Produces(MediaType.TEXT_PLAIN)
- public Response verifyRESTService(InputStream incomingData) {
- String result = "DemoRESTService Successfully started..";
- // return HTTP response 200 in case of success
- return Response.status(200).entity(result).build();
- }
- }
Deploy project DemoWS on Tomcat. Web project should be deployed without any exception.
Step-6 Verify REST service
Rest service should be accessible using this URL: http://127.0.0.1/DemoWS/api/verify
If you try to access http://127.0.0.1/DemoWS/api/demoService 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.
Step-7
Next we will post below json into server:
- {
- "tutorials": {
- "id": "Crunchify",
- "topic": "REST Service",
- "description": "This is REST Service Example by Crunchify."
- }
- }
- DemoRESTServiceClient.java
- package com.demo.tutorials;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.URL;
- import java.net.URLConnection;
- import org.json.JSONObject;
- public class DemoRESTServiceClient {
- public static void main(String args[]) throws Exception {
- // Step1:
- String jsonStr = "{\"tutorials\": {\"id\": \"Crunchify\",\"topic\": \"REST Service\",\"description\": \"This is REST Service Example by John.\"}}";
- JSONObject jsonObject = new JSONObject(jsonStr);
- // Step2: Now pass JSON File Data to REST Service
- try {
- URL url = new URL(
- "http://localhost/DemoWS/api/demoService");
- 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()));
- String line = null;
- while ((line=in.readLine()) != null) {System.out.printf("%s\n", line);}
- System.out.println("\nDemoWS REST Service Invoked Successfully..");
- in.close();
- } catch (Exception e) {
- System.out.println("\nError while calling DemoWS REST Service");
- System.out.println(e);
- }
- }
- }
Now let’s run Client Program by right click on DemoRESTServiceClient.java and you should see below two outputs:
1) in Tomcat Console
2) in Local Client Console
Supplement
* The Java EE 5 Tutorial - Building Web Services with JAX-WS
沒有留言:
張貼留言