Sai*_*hna 6 java graphql graphql-java
我必须发送一个带有一些标头和 graphQL 变量的查询作为对 java 中的 GraphQL API 的 POST 调用。我还必须在查询中发送一些标头和身份验证参数。现在,我正在 POSTMAN 中进行手动调用,但我想以编程方式执行此操作。你们能帮我从哪里开始吗?我的查询和变量如下
query sampleQuery($param: SampleQueryParams!, $pagingParam: PagingParams) {
sampleLookup(params: $param, pagingParams: $pagingParam) {
ID
name1
name2
}
}
Run Code Online (Sandbox Code Playgroud)
我的 GraphQL 变量如下:
{"param": {"id": 58763897}, "pagingParam": {"pageNumber": 0, "pageSize": 10 } }
Run Code Online (Sandbox Code Playgroud)
我不知道从哪里开始。你们能帮忙吗
下面是一个典型的 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 {...
Run Code Online (Sandbox Code Playgroud)
请注意,我们有 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();
}
Run Code Online (Sandbox Code Playgroud)
这里的 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())
Run Code Online (Sandbox Code Playgroud)
请注意 http post 的实现取决于后端 java 实现的设置方式
对于基本的 http 客户端和 post 设置,这里有很多很好的例子
How to use parameters with HttpPost
可能相关
graphql 允许内省流程,该流程发布有关查询结构的详细信息,该实现在此处支持更多信息
https://graphql.org/learn/introspection/
[1] https://github.com/graphql-java/graphql-java-examples