下面是一个典型的用于 java 后端的 graphql 端点
这里有2个基本流程
1 http 请求的端点,可以将 graghql 查询处理为字符串和查询输入变量的 map / json 表示形式
2 用于整理和返回数据的后端的 graphql 接线
后端通常会有一个看起来像这样 (1) 的端点
public Map<String, Object> graphqlGET(@RequestParam("query") String query,
@RequestParam(value = "operationName", required = false) String operationName,
@RequestParam("variables") String variablesJson) throws IOException {...
请注意,我们有 3 个输入
一个查询字符串,
查询变量的字符串通常为 json
一个可选的“操作名称”
一旦我们解析了这些输入参数,我们通常会将它们发送到 graphql 实现以进行查询
可能看起来像这样 (1)
private Map<String, Object> executeGraphqlQuery(String operationName,
String query, Map<String, Object> variables) {
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query(query)
.variables(variables)
.operationName(operationName)
.build();
return graphql.execute(executionInput).toSpecification();
}
这里的 graphql 对象具有返回数据的所有接线
所以一个解决方案就是将格式正确的输入参数发布到后端
我经常使用 android 和一个适用于旧 android 版本的 http 客户端,因此 kotlin 中的 post 请求可能看起来像这样一个非常简单的示例
val client = HttpClients.createDefault()
val httpPost = HttpPost(url)
val postParameters = ArrayList<NameValuePair>()
postParameters.add(BasicNameValuePair("query", "query as string"))
postParameters.add(BasicNameValuePair("variables", "variables json string"))
httpPost.entity = UrlEncodedFormEntity(postParameters, Charset.defaultCharset())
val response = client.execute(httpPost)
val ret = EntityUtils.toString(response.getEntity())
请注意http post的实现取决于后端java实现的设置方式
对于基本的 http 客户端和 post setup 这里有很多很好的例子
How to use parameters with HttpPost
可能相关
graphql 允许一个内省流程,该流程发布有关实现支持的查询结构的详细信息
更多信息在这里
https://graphql.org/learn/introspection/
[1]https://github.com/graphql-java/graphql-java-examples