創建非常簡單的 Jersey REST 服務並從 Java 客戶端發送 JSON 數據
已發表: 2013-11-29最近我必須將 JSON 數據傳遞給 REST 服務,並且手邊沒有任何簡單的客戶端。 但是創建了非常簡單的 Java 程序,它從文件中讀取 JSON 數據並將其發送到 REST 服務。
具象狀態轉移 (REST) 作為基於 SOAP 和 Web 服務描述語言 (WSDL) 的 Web 服務的更簡單替代方案,已在 Web 上獲得廣泛認可。 界面設計這一轉變的關鍵證據是主流 Web 2.0 服務提供商(包括 Yahoo、Google 和 Facebook)採用 REST,他們棄用或傳遞了基於 SOAP 和 WSDL 的界面,轉而支持更易於使用、面向資源的模型來公開他們的服務。 在本文中,Alex Rodriguez 向您介紹了 REST 的基本原理。
讓我們開始編寫代碼:
- 創建 RESTFul Web 服務
- Java 文件:CrunchifyRESTService.java
- web.xml 文件
- 創建 RESTService 客戶端
- CrunchifyRESTServiceClient.java 文件
另一個必須閱讀: Spring MVC 示例/教程:Hello World – Spring MVC 3.2.1
第1步
在Eclipse => File => New => Dynamic Web Project
中。 將其命名為“ CrunchifyTutorials
”。 下面的教程也適用於Tomcat 8
。
步驟 2 創建部署描述符文件
如果您在WebContent\WEB-INF\
下沒有看到web.xml
(部署描述符),請按照以下步驟操作。
打開web.xml
並將內容替換為以下內容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<? 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 將項目轉換為 Maven 項目
遵循本教程:https://crunchify.com/how-to-convert-existing-java-project-to-maven-in-eclipse/。 這是我的 pom.xml 文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 |
< 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 > |
第四步
創建 RESTFul 服務: CrunchifyRESTService.java
。 在這裡,我們將創建兩個服務:
-
/api/crunchifyService
– POST 調用 – 我們將在測試中使用它 /api/verify
- GET 調用 - 只是為了確保服務成功啟動
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 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 ( ) ; } } |

第 5 步
在 Tomcat 上部署項目CrunchifyTutorials
。 應毫無例外地部署 Web 項目。
- 在 Eclipse 中右鍵單擊
Servers tab
- 單擊
Add and Remove...
項目 - 將 Project CrunchifyTutorials 添加到右側
Configured:
側。 - 點擊
Publish
- 點擊
Start
Step-6 驗證 REST 服務
應該可以使用以下 URL 訪問休息服務:http://127.0.0.1:8080/CrunchifyTutorials/api/verify
如果您嘗試訪問 http://127.0.0.1:8080/CrunchifyTutorials/api/crunchifyService 那麼您將看到錯誤代碼405 - Method not allowed
- 這是有效的響應。 正如您所看到的,它是 POST 調用,並且應該期望請求中包含一些數據。
讓我們繼續前進。
第 7 步
複製下面的 JSON 內容並將其放在 Windows 的C:\\CrunchifyJSON.txt
文件或 Macbook 的/Users/<username>/Documents/CrunchifyJSON.txt
文件下。
1 2 3 4 5 6 7 |
{ "tutorials" : { "id" : "Crunchify" , "topic" : "REST Service" , "description" : "This is REST Service Example by Crunchify." } } |
步驟 8
創建 REST 調用客戶端: CrunchifyRESTServiceClient.java.
請在下面的程序中change path to CrunchifyJSON.txt
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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 54 55 56 57 58 59 60 61 62 63 64 |
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 ( ) ; } } } |
第 9 步
現在讓我們通過右鍵單擊 CrunchifyRESTServiceClient.java 來運行客戶端程序,您應該會看到以下兩個輸出
1) 在 Tomcat 控制台中
2) 在本地客戶端控制台中