且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Java 应用程序调用 GraphQL 端点

更新时间:2023-08-17 15:50:40

Netflix DGS 有 springboot 客户端库.

Netflix DGS has springboot client libraries .

参考:https://netflix.github.io/dgs/advanced/java-client/#http-client-wrapper

https://netflix.github.io/dgs/generate-code-from-schema/#generating-client-apis.

private RestTemplate dgsRestTemplate;

private static final String URL = "http://someserver/graphql";

private static final String QUERY = "{
" +
            "  ticks(first: %d, after:%d){
" +
            "    edges {
" +
            "      node {
" +
            "        route {
" +
            "          name
" +
            "          grade
" +
            "          pitches
" +
            "          location
" +
            "        }
" +
            "        
" +
            "        userStars
" +
            "      }
" +
            "    }
" +
            "  }
" +
            "}";

public List<TicksConnection> getData() {
    DefaultGraphQLClient graphQLClient = new DefaultGraphQLClient(URL);
    GraphQLResponse response = graphQLClient.executeQuery(query, new HashMap<>(), (url, headers, body) -> {
        /**
         * The requestHeaders providers headers typically required to call a GraphQL endpoint, including the Accept and Content-Type headers.
         * To use RestTemplate, the requestHeaders need to be transformed into Spring's HttpHeaders.
         */
        HttpHeaders requestHeaders = new HttpHeaders();
        headers.forEach(requestHeaders::put);

        /**
         * Use RestTemplate to call the GraphQL service. 
         * The response type should simply be String, because the parsing will be done by the GraphQLClient.
         */
        ResponseEntity<String> exchange = dgsRestTemplate.exchange(url, HttpMethod.POST, new HttpEntity(body, requestHeaders), String.class);

        /**
         * Return a HttpResponse, which contains the HTTP status code and response body (as a String).
         * The way to get these depend on the HTTP client.
         */
        return new HttpResponse(exchange.getStatusCodeValue(), exchange.getBody());
    }); 

    TicksConnection ticks = graphQLResponse.extractValueAsObject("ticks", TicksConnection.class);
    return ticks;
}