0
0

WebClientを用いての外部APIの呼び出し方

Posted at

Java SpringBoot内でのWebClientを用いての外部APIの呼び出し方

※共通は各通信の場合で呼ばれているメソッド

(共通)

WebClientInfo.java
    public WebClient webClient;

    public WebClientInfo(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://localhost:8082").build();
    }

(GET通信の場合) ※クエリパラメータ方式の場合

WebClientInfo.java

    public 戻りの型 メソッド名(値1, 値2) {
        return this.webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/【URL】")
                        .queryParam("【パラメータ1】", 値1)
                        .queryParam("【パラメータ2】", 値2)
                        .build())
                .retrieve()
                .bodyToMono(戻りの型 .class).block();
    }
例)
    public ShukanTalentJoho getShukanTalentJoho(Integer nentsuki, Integer shu, String talentName) {
        return this.webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/shukanTalentJoho")
                        .queryParam("nentsuki", nentsuki)
                        .queryParam("shu", shu)
                        .queryParam("talentName", talentName)
                        .build())
                .retrieve()
                .bodyToMono(ShukanTalentJoho.class).block();
    }

(GET通信の場合) ※パスパラメータ方式の場合

WebClientInfo.java
    public 戻りの型 メソッド名(値1) {
        return this.webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/【URL】/{【パラメータ1】}")
                        .build(値1))
                .retrieve()
                .bodyToMono(戻りの型.class).block();
    }
例)
    public KbnMasterInfo getKbnMaster(String genreIds) {
        return this.webClient.get()
                .uri(uriBuilder -> uriBuilder
                        .path("/kbnMaster/{genreIds}")
                        .build(genreIds))
                .retrieve()
                .bodyToMono(KbnMasterInfo.class).block();
    }

(POST通信の場合) 

WebClientInfo.java
    public 戻りの型 メソッド名(値1) {
        return this.webClient.post()
	    		.uri("/【URL】")
	    	    .body(Mono.just(値1), 値1の型.class)
	    	    .accept(MediaType.APPLICATION_JSON)
	    	    .retrieve()
	    	    .bodyToMono(戻りの型.class).block();
    }
例)
    public TalentTorokuKoshinBFF postTalentTorokuKoshin(MTalent mTalent) {
        return this.webClient.post()
	    		.uri("/talentTorokuKoshin")
	    	    .body(Mono.just(mTalent), MTalent.class)
	    	    .accept(MediaType.APPLICATION_JSON)
	    	    .retrieve()
	    	    .bodyToMono(TalentTorokuKoshinBFF.class).block();
    }

上記が各通信方式となります。

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