LoginSignup
0
0

More than 3 years have passed since last update.

API呼ぶ【コア編】

Last updated at Posted at 2019-12-26

API呼ぶ

以下4つのパートに分かれています。(〇〇編は適当につけましたゆるして)
API呼ぶ【準備編】
API呼ぶ【コア編】
API呼ぶ【ハンドリング編】
API呼ぶ【コール編】

コア編

実際にAPIにPOST送信をなげる、コアとなる部分を実装します

client.java
package client;

import javax.xml.ws.http.HTTPException;

import json.JsonUtil;
import model.RequestDto;
import model.ResponseDto;

public class Client {

    /**
     * APIを実行する
     * 
     * @param request リクエストDTO
     * @return レスポンスDTO
     */
    public ResponseDto nantokaApiClient(RequestDto request) {

        String requestJson = JsonUtil.requestDtoToJson(request);

        String response = post(requestJson, "http://nantoka.com");

        return JsonUtil.responseJsonToDto(response);
    }

    /**
     * POST処理
     * 
     * @param requestJson Json変換したリクエスト
     * @param uri 送信先URI
     * @return レスポンスJson
     * @throws 通信エラー系
     */
    private final String post(String requestJson, String uri) {

        try {
            // なんかPOST用のライブラリのやつ
            return "ClientBuilder.newClient().path(uri).request().post(requestJson);";
        } catch (HTTPException e) {
            throw e;
        }
    }
}

postメソッド内部の実際のClientBuilderのライブラリは今回は省略しました
ハンドリングはもっと表面部分の階層の処理でやりたいため、
今回みたいなコア層では通信系Exceptionをすべてそのままスローするようにしています

やってることはリクエストを投げてレスポンスを受け取る、ただそれだけですね
外部のメソッドを通信して使ってるだけです
通信の際にはJson形式に直して送り、戻ってきたJson結果をDTOに直して返してます

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0