如何从Java应用程序调用GraphQL端点 [英] How to make a call to a GraphQL endpoint from a Java application
本文介绍了如何从Java应用程序调用GraphQL端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试调用GraphQL端点(外部的,不受我控制),我在互联网上只能找到如何使用Java Spring Boot设置后端GraphQL端点.如何从Java应用程序调用GraphQL端点?
I am trying to make a call to a GraphQL endpoint (external, not controlled by me), all I can find on internet is how to setup a back-end GraphQL endpoint using Java Spring Boot. How do I call a GraphQL endpoint from a Java application?
推荐答案
Netflix DGS具有springboot客户端库.
Netflix DGS has springboot client libraries .
Ref: https://netflix.github.io/dgs/advanced/java-client/#http-client-wrapper
和
https://netflix.github.io/dgs/generating-code-from-schema/#generating-client-apis .
private RestTemplate dgsRestTemplate;
private static final String URL = "http://someserver/graphql";
private static final String QUERY = "{\n" +
" ticks(first: %d, after:%d){\n" +
" edges {\n" +
" node {\n" +
" route {\n" +
" name\n" +
" grade\n" +
" pitches\n" +
" location\n" +
" }\n" +
" \n" +
" userStars\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
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;
}
这篇关于如何从Java应用程序调用GraphQL端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文