12.5.2 Webリソースクライアントの実装クラスを作成する(java.net.HttpURLConnectionを利用する)

HttpURLConnectionクラスを利用するクライアントの実装クラスを作成します。

例を次に示します。

package com.sample.client;

import java.net.URL;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

//サンプル:Webリソースのクライアントの実行
public class SampleClient {

   public static void main(String[] args) {
       
       final String HOST = args[0];
       final String PORT = args[1];
       
       SampleClient sampleClient = new SampleClient();
       
       try{
           sampleClient.demonstration1(HOST, PORT);
           sampleClient.demonstration2(HOST, PORT);
           
           System.out.println("¥n----- Successfully Ended -----");
           
       }catch(Exception e){
           //詳細な例外のメッセージを表示する
           System.out.println(e.getMessage());
       }
   }

   private void demonstration1(String HOST, String PORT) {

       System.out.println("¥n Demonstration 1 started.");
       System.out.println(" This demonstrates injection of " +
               "javax.ws.rs.core.Request instance " +
               "onto resource class field by using @Context.");
       
       URL url = null;
       HttpURLConnection httpConn = null;

       Map<String, List<String>> headers = null;
       List<String> status = null;
       String responseEntity = "";
       
       //Webリソースを呼び出す
       try {
           //呼び出す対象のWebリソースのURIを設定する
           url = new URL("http://" + HOST + ":" + PORT+
                   "/tutorial/root");
           //初回接続をセットアップする
           httpConn = (HttpURLConnection) url.openConnection();
           //HTTP()メソッドを"GET"に設定する
           httpConn.setRequestMethod("GET");
           //接続を開始する
           httpConn.connect();
       }catch (MalformedURLException e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 1 failed.");
       }catch (IOException e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 1 failed.");
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 1 failed.");
       }

       System.out.println(" The target URL is ¥"" + url + "¥".");
       System.out.println(" The HTTP method  is " + "¥"GET¥"" + ".");

       try {
           //HTTPレスポンスのヘッダを取得する
           headers = httpConn.getHeaderFields();
           //ヘッダからHTTPステータスを取得する
           status = headers.get(null);
           //入力ストリームリーダを取得してHTTPレスポンスの
           //エンティティボディを読み込む
           BufferedReader rd = new BufferedReader(new InputStreamReader(
               httpConn.getInputStream()));
           String line = "";
           while ((line = rd.readLine()) != null) {
               responseEntity += line;
           }
           //入力ストリームリーダを閉じる
           rd.close();
           //接続を終了する
           httpConn.disconnect();
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 1 failed.");
       }
       
       System.out.println(" Connection and interaction ended successfully.");

       //ステータスコードとエンティティボディの期待値を設定する
       String statusExpect = "[HTTP/1.1 200 OK]";
       String responseEntityExpect = "RequestMethod: GET";
       
       //ステータスコードとエンティティボディが期待値と同じかチェックする
       if (status.toString().equals(statusExpect)
               & responseEntity.equals(responseEntityExpect)) {
           //HTTPヘッダを表示する
           System.out.println(" Response headers are " + headers.toString() + ".");
           //エンティティボディを表示する
           System.out.println(" Response entity is " + responseEntity + ",");
           System.out.println(" which means target resource completed " +
                   "the process described above without any problem.");
           
           System.out.println(" Demonstration 1 ended successfully.");
       }else {
           System.out.println(" The response is not as expected.");
           throw new RuntimeException(" Demonstration 1 failed.");
       }
   
   private void demonstration2(String HOST, String PORT) {

       System.out.println("¥n Demonstration 2 started.");
       System.out.println(" This demonstrates injection of QueryParam " +
               "onto resource bean setter method by using @QueryParam.");

       URL url = null;
       HttpURLConnection httpConn = null;
       String responseEntity = "";
       Map<String, List<String>> headers = null;
       List<String> status = null;
       
       //Webリソースを呼び出す
       try {
           //呼び出す対象のWebリソースのURIを設定する
           //URIにクエリパラメタを付与する

           url = new URL("http://" + HOST + ":" + PORT+
                   "/tutorial/root/getQueryParam?queryParam=queryValue");
           //初回接続をセットアップする
           httpConn = (HttpURLConnection) url.openConnection();
           //HTTP()メソッドを"GET"に設定する
           httpConn.setRequestMethod("GET");
           //接続を開始する
           httpConn.connect();
       }catch (MalformedURLException e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 2 failed.");
       }catch (IOException e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 2 failed.");
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 2 failed.");
       }

       System.out.println(" The target URL is ¥"" + url + "¥".");
       System.out.println(" The HTTP method  is " + "¥"GET¥"" + ".");
       
       try {
           //HTTPヘッダを取得する
           headers = httpConn.getHeaderFields();
           //HTTPヘッダからのステータスコードを取得する
           status = headers.get(null);
           //入力ストリームリーダを取得してHTTPレスポンスの
           //エンティティボディを読み込む
           BufferedReader rd = new BufferedReader(new InputStreamReader(
               httpConn.getInputStream()));
           String line = "";
           while ((line = rd.readLine()) != null) {
               responseEntity += line;
           }
           //入力ストリームリーダを閉じる
           rd.close();
           //接続を終了する
           httpConn.disconnect();
       }catch (Exception e) {
           System.out.println(" ERROR: " + e.getClass() + " was thrown. ");
           //スタックトレースを表示する
           e.printStackTrace();
           throw new RuntimeException(" Demonstration 2 failed.");
       }
       
       System.out.println(" Connection and interaction ended successfully.");
       
       //ステータスコードとエンティティボディの期待値を設定する
       String statusExpect = "[HTTP/1.1 200 OK]";
       String responseEntityExpect = "QueryParameter: queryValue";
       
       //ステータスコードとエンティティボディが期待値と同じかチェックする
       if (status.toString().equals(statusExpect)
               & responseEntity.equals(responseEntityExpect)) {
           //HTTPヘッダを表示する
           System.out.println(" Response headers are " + headers.toString() + ".");
           //エンティティボディを表示する
           System.out.println(" Response entity is " + responseEntity + ",");
           System.out.println(" which means target resource completed " +
                   "the process described above without any problem.");
           
           System.out.println(" Demonstration 2 ended successfully.");
       }else {
           System.out.println(" The response is not as expected.");
           throw new RuntimeException(" Demonstration 2 failed.");
       }
       
   }
   }

}

作成したSampleClient.javaは,UTF-8形式でc:¥temp¥jaxrs¥works¥tutorial¥client¥src¥com¥sample¥client¥ディレクトリに保存します。