非常にシンプルなJerseyRESTサービスを作成し、JavaクライアントからJSONデータを送信する
公開: 2013-11-29最近、JSONデータをRESTサービスに渡す必要があり、簡単なクライアントが手元にありませんでした。 しかし、ファイルからJSONデータを読み取り、それをRESTサービスに送信する非常に単純なJavaプログラムを作成しました。
Representational State Transfer(REST)は、SOAPおよびWebサービス記述言語(WSDL)ベースのWebサービスのより単純な代替手段として、Web全体で広く受け入れられています。 このインターフェース設計の変化の主な証拠は、Yahoo、Google、Facebookなどの主流のWeb 2.0サービスプロバイダーがRESTを採用していることです。これらのプロバイダーは、SOAPおよびWSDLベースのインターフェースを廃止または受け継いでおり、使いやすく、サービスを公開するためのリソース指向モデル。 この記事では、AlexRodriguezがRESTの基本原則を紹介します。
これをコーディングし始めましょう:
- RESTFulWebサービスを作成する
- Javaファイル:CrunchifyRESTService.java
- web.xmlファイル
- RESTServiceクライアントを作成する
- CrunchifyRESTServiceClient.javaファイル
もう1つ読む必要があります: Spring MVCの例/チュートリアル:Hello World – Spring MVC 3.2.1
ステップ1
Eclipse => File => New => Dynamic Web Project
。 「 CrunchifyTutorials
」という名前を付けます。 以下のチュートリアルはTomcat8でも機能し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 > |
ステップ-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 > |
ステップ-4
RESTFulサービスを作成します: CrunchifyRESTService.java
。 ここでは、2つのサービスを作成します。
-
/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
プロジェクトCrunchifyTutorials
をTomcatにデプロイします。 Webプロジェクトは例外なく展開する必要があります。
- Eclipseの[
Servers tab
を右クリックします - [
Add and Remove...
]プロジェクトをクリックします - Project CrunchifyTutorialsを右側の
Configured:
側に追加します。 - [
Publish
をクリックします - [
Start
クリックします
ステップ-6RESTサービスを確認する
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を右クリックしてクライアントプログラムを実行すると、以下の2つの出力が表示されます。
1)Tomcatコンソールで
2)ローカルクライアントコンソールで