项目地址 :github.com/MountCloud/...
简介 :graphql-client
是一个轻量级的 Java GraphQL 客户端库,支持发送查询(Query)和变更(Mutation)请求,适用于与 GraphQL 服务端交互。
一、快速开始
1. 环境准备
- 依赖添加:在 Maven 项目中引入以下依赖(确保版本 ≥1.2,旧版本可能缺少关键功能):
xml
<dependency>
<groupId>org.mountcloud</groupId>
<artifactId>graphql-client</artifactId>
<version>1.2</version>
</dependency>
注意:1.1 版本不支持 addObjectParameter
方法。 提示:因为这个项目很久没有更新了,这里不建议直接使用jar包,最好自己把代码拉下来,复制到项目里面去,方便扩展。
2. 初始化客户端
java
String serverUrl = "http://localhost:8080/graphql";
GraphqlClient client = GraphqlClient.buildGraphqlClient(serverUrl);
// 设置请求头(如认证 Token)
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer YOUR_TOKEN");
client.setHttpHeaders(headers);
二、基本使用
1. 发送简单查询
java
// 创建查询对象,指定查询名称
GraphqlQuery query = new DefaultGraphqlQuery("findUser");
// 添加参数(参数需与服务端定义一致)
query.addParameter("id", 1);
// 指定返回字段
query.addResultAttributes("name", "age", "email");
try {
GraphqlResponse response = client.doQuery(query);
Map<String, Object> data = response.getData();
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
生成的 GraphQL 语句:
graphql
query {
findUser(id: 1) {
name
age
email
}
}
2. 发送复杂查询(嵌套字段)
java
// 查询用户的部门及公司信息
ResultAttributes departmentAttr = new ResultAttributes("department");
departmentAttr.addResultAttributes("name", "code");
ResultAttributes companyAttr = new ResultAttributes("company");
companyAttr.addResultAttributes("name");
departmentAttr.addResultAttributes(companyAttr);
query.addResultAttributes(departmentAttr);
生成的 GraphQL 语句:
graphql
query {
findUser(id: 1) {
name
department {
name
code
company {
name
}
}
}
}
三、高级功能
1. 发送变更(Mutation)
java
GraphqlMutation mutation = new DefaultGraphqlMutation("updateUser");
mutation.addParameter("id", 12)
.addParameter("name", "张三")
.addParameter("age", 24);
mutation.addResultAttributes("code", "message");
try {
GraphqlResponse response = client.doMutation(mutation);
Map<String, Object> result = response.getData();
} catch (IOException e) {
e.printStackTrace();
}
2. 传递复杂对象参数
若需传递对象或枚举类型,使用 addObjectParameter
:
java
List<User> users = new ArrayList<>();
users.add(new User("Tim", SexEnum.M));
users.add(new User("Alice", SexEnum.F));
mutation.addParameter("classId", "123")
.addObjectParameter("users", users); // 注意:对象参数不能作为第一个参数:cite[3]
四、常见问题与解决方案
1. 参数传递失败
- 问题 :复杂对象参数未正确序列化。
解决 :使用addObjectParameter
方法,并确保参数顺序正确(非第一个参数位置)。
2. 如何在一个请求中执行多个查询?
- 问题:例如以下查询。
graphql
query{
findUsers(sex:"man",age:11){
id
name
age
sex
class{
name
code
school{
name
}
}
}
findUsers1(sex:"man",age:11){
id
name
age
sex
class{
name
code
school{
name
}
}
}
}
- 解决方案: 这里就需要添加扩展,所以上面建议把代码拉取使用
GraphqlQueryObject.java
java
package org.mountcloud.graphql.request.query;
import org.mountcloud.graphql.request.GraphqlRequest;
import org.mountcloud.graphql.request.param.RequestParameter;
import org.mountcloud.graphql.request.result.ResultAttributtes;
import java.util.ArrayList;
import java.util.List;
public class GraphqlQueryObject extends GraphqlQuery {
protected String requestName;
protected RequestParameter requestParameter = RequestParameter.build();
protected List<ResultAttributtes> resultAttributes = new ArrayList<ResultAttributtes>();
protected ArrayList<GraphqlQueryObject> subQueryObjects = new ArrayList();
public GraphqlQueryObject(String requestName) {
super(requestName);
this.requestName = requestName;
}
public RequestParameter addParameter(String key, Object val) {
return this.requestParameter.addParameter(key, val);
}
public GraphqlRequest addResultAttributes(String... resultAttribute) {
if(resultAttribute!= null && resultAttribute.length > 0){
for(String str : resultAttribute){
ResultAttributtes ra = new ResultAttributtes(str);
resultAttributes.add(ra);
}
}
return null;
}
public String toString() {
StringBuffer requestBuffer = new StringBuffer(requestName);
//参数列表字符串
String paramStr = requestParameter.toString();
StringBuilder resultAttrBuffer = new StringBuilder("");
boolean first = true;
//第一个前面不拼接","
for(ResultAttributtes ra :resultAttributes) {
if(first) {
first = false;
}else{
resultAttrBuffer.append(" ");
}
resultAttrBuffer.append(ra.toString());
}
String resultAttrStr = resultAttrBuffer.toString();
requestBuffer.append(paramStr);
requestBuffer.append("{");
requestBuffer.append(resultAttrStr);
// subQueryObjects
if( subQueryObjects.size() != 0) {
for (GraphqlQueryObject subQueryObject : subQueryObjects)
requestBuffer.append(" " + subQueryObject.toString());
}
requestBuffer.append("}");
if (this.requestName.equals("query")) {
return "{\"query\":\"" + requestBuffer.toString() + "\"}";
}
return requestBuffer.toString();
}
public void put(GraphqlQueryObject subQueryObject) {
subQueryObjects.add(subQueryObject);
}
}
测试代码可以不要:
GraphqlClientTest.java
java
package org.mountcloud.graphql;
import org.junit.Test;
import org.mountcloud.graphql.request.mutation.DefaultGraphqlMutation;
import org.mountcloud.graphql.request.mutation.GraphqlMutation;
import org.mountcloud.graphql.request.query.DefaultGraphqlQuery;
import org.mountcloud.graphql.request.query.GraphqlQuery;
import org.mountcloud.graphql.request.query.GraphqlQueryObject;
import org.mountcloud.graphql.request.result.ResultAttributtes;
import org.mountcloud.graphql.response.GraphqlResponse;
import java.io.IOException;
import java.util.*;
public class GraphqlClientTest {
@Test
public void simpleQuery(){
//graphql服务器地址
String serverUrl = "http://localhost:8080/graphql";
//build一个新的graphqlclient
GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
//如果说graphql需要健全信息我们可以用map来进行传递
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("token","graphqltesttoken");
//设置http请求的头
graphqlClient.setHttpHeaders(httpHeaders);
//创建一个Query并设置query的名字为findUser
GraphqlQuery query = new DefaultGraphqlQuery("findUser");
//我们需要查询user的 name,sex还有age,设置需要查询的这三个属性。
query.addResultAttributes("name","sex","age");
System.out.println(query.toString());
//创建一个mutation并设置名字为updateUser
GraphqlMutation mutation = new DefaultGraphqlMutation("updateUser");
mutation.addResultAttributes("name","sex","age");
System.out.println(mutation.toString());
}
@Test
public void testObjectParameter() throws IOException {
//graphql服务器地址
String serverUrl = "http://localhost:8080/graphql";
//build一个新的graphqlclient
GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
//如果说graphql需要健全信息我们可以用map来进行传递
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("token","graphqltesttoken");
//设置http请求的头
graphqlClient.setHttpHeaders(httpHeaders);
//创建一个Mutation并设置mutation的名字为addUser
GraphqlMutation mutation = new DefaultGraphqlMutation("addUser");
List<User> users = new ArrayList<>();
users.add(new User("tim",SexEnum.M));
users.add(new User("sdf",SexEnum.F));
mutation.getRequestParameter().addParameter("classId","123").addObjectParameter("users",users);
//返回code
mutation.addResultAttributes("code");
System.out.println(mutation.toString());
}
/**
* test user
*/
class User{
public User(String name, SexEnum sexEnum) {
this.name = name;
this.sexEnum = sexEnum;
}
private String name;
private SexEnum sexEnum;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SexEnum getSexEnum() {
return sexEnum;
}
public void setSexEnum(SexEnum sexEnum) {
this.sexEnum = sexEnum;
}
}
/**
* test user sex
*/
enum SexEnum{
M,
F
}
@Test
public void testMultipleQuery(){
/*
// Statement to be tested
query{
findUsers(sex:"man",age:11){
id
name
age
sex
class{
name
code
school{
name
}
}
}
findUsers1(sex:"man",age:11){
id
name
age
sex
class{
name
code
school{
name
}
}
}
}
*/
//graphql服务器地址
String serverUrl = "http://localhost:8080/graphql";
//build一个新的graphqlclient
GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
//如果说graphql需要健全信息我们可以用map来进行传递
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("token","graphqltesttoken");
// shool
GraphqlQueryObject school = new GraphqlQueryObject("school");
school.addResultAttributes("name");
// class
GraphqlQueryObject class_1 = new GraphqlQueryObject("class");
class_1.addResultAttributes("name");
class_1.addResultAttributes("code");
class_1.put(school);
// findUsers
GraphqlQueryObject findUsers = new GraphqlQueryObject("findUsers");
findUsers.addResultAttributes("id");
findUsers.addResultAttributes("name");
findUsers.addResultAttributes("age");
findUsers.addResultAttributes("sex");
findUsers.put(class_1);
// findUsers1
GraphqlQueryObject findUsers1 = new GraphqlQueryObject("findUsers1");
findUsers1.addResultAttributes("id");
findUsers1.addResultAttributes("name");
findUsers1.addResultAttributes("age");
findUsers1.addResultAttributes("sex");
findUsers1.put(class_1);
// query
GraphqlQueryObject query = new GraphqlQueryObject("query");
query.put(findUsers);
query.put(findUsers1);
System.out.println(query.toString());
}
@Test
public void testInternalObjectParameter(){
//
/* Statement to be tested
query{
worldData{
zones(expansion_id: null){
id
name
}
}
}
*/
//graphql服务器地址
String serverUrl = "http://localhost:8080/graphql";
//build一个新的graphqlclient
GraphqlClient graphqlClient = GraphqlClient.buildGraphqlClient(serverUrl);
//如果说graphql需要健全信息我们可以用map来进行传递
Map<String,String> httpHeaders = new HashMap<>();
httpHeaders.put("token","graphqltesttoken");
//设置http请求的头
graphqlClient.setHttpHeaders(httpHeaders);
// Zones
GraphqlQueryObject zones = new GraphqlQueryObject("zones");
zones.addParameter("expansion_id", null);
zones.addResultAttributes("id");
zones.addResultAttributes("name");
// WorldData
GraphqlQueryObject worldData = new GraphqlQueryObject("worldData");
worldData.put(zones);
// Query
GraphqlQueryObject query = new GraphqlQueryObject("query");
query.put(worldData);
System.out.println(query.toString());
}
}
3. 请求返回on Type{}怎么用?
- 问题:示例。
graphql
mutation a($demo: String!) {
updateCustomer(demo: $demo) {
... on MutationSuccess {
result
}
... on MutationError {
errorCode
}
}
}
解决
java
ResultAttributtes classAttributte = new ResultAttributtes("... on MutationSuccess");
问题持续更新中。。。。。。
总结
MountCloud 的 graphql-client
是一个简单高效的 Java GraphQL 客户端,适合快速集成。通过合理使用查询、变更和复杂参数功能,结合错误处理和版本控制,可显著提升开发效率。若遇到问题,优先检查参数顺序、依赖版本和网络配置