2017年1月12日 星期四

[ Java 文章收集 ] Create Very Simple Jersey REST Service and Send JSON Data From Java Client

Source From Here 
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 
* Java file: DemoRESTService.java
* web.xml file

2. Create RESTService Client 
* DemoRESTServiceClient.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 “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: 
1. /api/demoService – POST call – we will use this with our test
2. /api/verify – GET call – just to make sure service started successfully

  1. package com.demo.tutorials;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6.   
  7. import javax.ws.rs.Consumes;  
  8. import javax.ws.rs.GET;  
  9. import javax.ws.rs.POST;  
  10. import javax.ws.rs.Path;  
  11. import javax.ws.rs.Produces;  
  12. import javax.ws.rs.core.MediaType;  
  13. import javax.ws.rs.core.Response;  
  14.   
  15. @Path("/")  
  16. public class DemoRESTService {  
  17.     @POST  
  18.     @Path("/demoService")  
  19.     @Consumes(MediaType.APPLICATION_JSON)  
  20.     public Response crunchifyREST(InputStream incomingData) {  
  21.         StringBuilder strBuilder = new StringBuilder();  
  22.         try {  
  23.             BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));  
  24.             String line = null;  
  25.             while ((line = in.readLine()) != null) {  
  26.                 strBuilder.append(line);  
  27.             }  
  28.         } catch (Exception e) {  
  29.             System.out.println("Error Parsing: - ");  
  30.         }  
  31.         System.out.println("Data Received: " + strBuilder.toString());  
  32.   
  33.         // return HTTP response 200 in case of success  
  34.         return Response.status(200).entity(strBuilder.toString()).build();  
  35.     }  
  36.   
  37.     @GET  
  38.     @Path("/verify")  
  39.     @Produces(MediaType.TEXT_PLAIN)  
  40.     public Response verifyRESTService(InputStream incomingData) {  
  41.         String result = "DemoRESTService Successfully started..";  
  42.   
  43.         // return HTTP response 200 in case of success  
  44.         return Response.status(200).entity(result).build();  
  45.     }  
  46. }  
Step-5 
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: 
  1. {  
  2.     "tutorials": {  
  3.         "id""Crunchify",  
  4.         "topic""REST Service",  
  5.         "description""This is REST Service Example by Crunchify."  
  6.     }  
  7. }  
Create REST Call Client: 
- DemoRESTServiceClient.java 
  1. package com.demo.tutorials;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.InputStreamReader;  
  5. import java.io.OutputStreamWriter;  
  6. import java.net.URL;  
  7. import java.net.URLConnection;  
  8.   
  9. import org.json.JSONObject;  
  10.   
  11. public class DemoRESTServiceClient {  
  12.     public static void main(String args[]) throws Exception {  
  13.         // Step1:   
  14.         String jsonStr = "{\"tutorials\": {\"id\": \"Crunchify\",\"topic\": \"REST Service\",\"description\": \"This is REST Service Example by John.\"}}";  
  15.         JSONObject jsonObject = new JSONObject(jsonStr);  
  16.           
  17.         // Step2: Now pass JSON File Data to REST Service  
  18.         try {  
  19.             URL url = new URL(  
  20.                     "http://localhost/DemoWS/api/demoService");  
  21.             URLConnection connection = url.openConnection();  
  22.             connection.setDoOutput(true);  
  23.             connection.setRequestProperty("Content-Type""application/json");  
  24.             connection.setConnectTimeout(5000);  
  25.             connection.setReadTimeout(5000);  
  26.             OutputStreamWriter out = new OutputStreamWriter(  
  27.                     connection.getOutputStream());  
  28.             out.write(jsonObject.toString());  
  29.             out.close();  
  30.   
  31.             BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
  32.   
  33.             String line = null;  
  34.             while ((line=in.readLine()) != null) {System.out.printf("%s\n", line);}  
  35.             System.out.println("\nDemoWS REST Service Invoked Successfully..");  
  36.             in.close();  
  37.         } catch (Exception e) {  
  38.             System.out.println("\nError while calling DemoWS REST Service");  
  39.             System.out.println(e);  
  40.         }  
  41.     }  
  42. }  
Step-9 
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

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...