Javaを用いたHTTPリクエストの送信とレスポンス解析の手順

HTTPクライアントを使用してリクエストを送信し、サーバーからのレスポンスを解析するプロセスは、以下の手順で構成されます。まず、通信目的に応じたHTTPメソッド(PUT、POST、GET等)のオブジェクトを定義します。次に、日付や認証情報などの必須ヘッダーをリクエストに設定します。その後、XMLなどの送信データをHttpEntityとしてカプセル化し、リクエストオブジェクトに紐付けます。HttpClientのインスタンスを生成してリクエストを実行し、返却されたHttpResponseからステータスコード、各種ヘッダー、およびレスポンスボディの内容を抽出して処理を行います。

実装コード

以下のサンプルコードは、Apache HttpClientライブラリを使用してキューの属性変更を行うPUTリクエストを作成し、送信からレスポンス受信までの一連の処理を実装したものです。

public void updateQueueConfiguration() {
    // HttpClientの生成(Apache HttpClient 4.x以降の推奨される実装)
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        
        // リクエスト先URLの構築
        String targetUrl = endpointHost + "/" + queueName + "?Metaoverride=true";
        HttpPut httpPut = new HttpPut(targetUrl);
        
        // ヘッダー情報の設定
        httpPut.setHeader("Date", timestamp);
        System.out.println("Date:" + timestamp);
        
        httpPut.setHeader("x-mqs-version", apiVersion);
        System.out.println("x-mqs-version:" + apiVersion);
        
        httpPut.setHeader("Authorization", signature);
        System.out.println("Authorization:" + signature);
        
        httpPut.setHeader("Content-Type", "text/xml;charset=utf-8");

        // リクエストボディ(XML)の構築
        String payload = buildXmlPayload();
        System.out.println("\n" + payload);
        
        // HttpEntityの設定とリクエストへの紐付け
        StringEntity requestEntity = new StringEntity(payload, StandardCharsets.UTF_8);
        httpPut.setEntity(requestEntity);    
        
        // リクエストの実行とHttpResponseの取得
        try (CloseableHttpResponse response = client.execute(httpPut)) {
            
            // ステータスコードの取得
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("Status Code: " + statusCode);
            
            // レスポンスヘッダーの処理
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                String name = header.getName();
                // 必要なヘッダー(Content-Length, Server等)のチェック
                if (Arrays.asList("Content-Length", "Connection", "Date", "Server", "x-mqs-request-id", "x-mqs-version").contains(name)) {
                    // 必要に応じてログ出力などを実装
                }
            }
            
            // レスポンスボディの読み取り
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                System.out.println("Response:" + "\n" + responseBody);
                // 接続を再利用するためにエンティティを消費
                EntityUtils.consume(responseEntity);
            }
        }
    } catch (Exception e) {
        System.err.println("Error occurred: " + e.toString());
    }
}

/**
 * キュー設定用のXML文字列を生成するメソッド
 */
private String buildXmlPayload() {
    StringBuilder xmlBuilder = new StringBuilder();
    xmlBuilder.append("");
    xmlBuilder.append("<Queue xmlns=\"http://mqs.aliyuncs.com/doc/v1/\">");
    xmlBuilder.append("<VisibilityTimeout>120</VisibilityTimeout>");
    xmlBuilder.append("<MaximumMessageSize>1024</MaximumMessageSize>");
    xmlBuilder.append("<MessageRetentionPeriod>120</MessageRetentionPeriod>");
    xmlBuilder.append("<DelaySeconds>60</DelaySeconds>");
    xmlBuilder.append("</Queue>");
    return xmlBuilder.toString();
}

実行結果

署名の検証に失敗した場合など、リクエスト処理に問題があるとサーバーは以下のようなHTTP 403エラーレスポンスを返します。

Status Code: 403
Response:

<Error xmlns="http://mqs.aliyuncs.com/doc/v1">
  SignatureDoesNotMatch
  <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
  <RequestId>53D60FE4048A936A361D8ABA</RequestId>
  <HostId>http://huvaw6yih3.mqs-cn-hangzhou.aliyuncs.com</HostId>
</Error>

タグ: Java Apache HttpClient HTTP

5月22日 06:35 投稿