스프링 WebClient로 graphql 서버에 요청응답받기

728x90
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.0.2</version>
</dependency>
<dependency>
    <groupId>com.graphql-java-kickstart</groupId>
    <artifactId>graphql-webclient-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>
WebClient 가 webflux에 포함되어 있습니다.
WebClient webClient = WebClient
    .builder()
    .baseUrl("https://apijosu.com/graphql")
    .defaultHeader("Authorization", "Bearer user token")
    .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
    .build();

WebClient로 get, post 요청 필요한 헤더를 넣고 url을 지정합니다.

GraphQLRequest request = GraphQLRequest.builder().query("query").build()

WebClient 에서 query를 지정해서 get은 queryparam, post는 body에 데이터를 넣고 전송할 수 있으나, graphql 쿼리문 문자열 인식이 에러가 납니다.
GraphQLRequest 를 사용해 request 를 만들어줍니다.

String block = webClient.post().bodyValue(request.getRequestBody()).retrieve().bodyToMono(String.class).block();
System.out.println(block);


해당 request 에 바디를 가져와서 post 요청합니다.

반응형