1. 环境准备
Spring Boot 版本:2.x 或 3.x。
JDK 版本:8 或更高。
依赖:需要
spring-boot-starter-web
和httpclient
。
2. 添加依赖
在 pom.xml
中添加以下依赖:
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- JSON 处理 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
3. 创建 GraphQL 请求工具类
创建一个工具类 GraphQLClient
,用于发送 GraphQL 请求。
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class GraphQLClient {
private static final String GRAPHQL_URL = "https://your-graphql-endpoint.com/graphql"; // 替换为你的 GraphQL 接口地址
private final CloseableHttpClient httpClient;
private final ObjectMapper objectMapper;
public GraphQLClient() {
this.httpClient = HttpClients.createDefault();
this.objectMapper = new ObjectMapper();
}
/**
* 发送 GraphQL 请求
*
* @param query GraphQL 查询语句
* @param variables 查询变量
* @return 响应结果
*/
public String executeQuery(String query, Map<String, Object> variables) throws IOException {
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("query", query);
requestBody.put("variables", variables);
// 将请求体转换为 JSON
String requestBodyJson = objectMapper.writeValueAsString(requestBody);
// 创建 HTTP POST 请求
HttpPost httpPost = new HttpPost(GRAPHQL_URL);
httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
httpPost.setEntity(new StringEntity(requestBodyJson, ContentType.APPLICATION_JSON));
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
return EntityUtils.toString(response.getEntity());
}
}
/**
* 关闭 HttpClient
*/
public void close() throws IOException {
httpClient.close();
}
}
4. 使用 GraphQLClient 调用接口
在 Spring Boot 服务中使用 GraphQLClient
调用 GraphQL 接口。
(1)创建服务类
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Service
public class GraphQLService {
private final GraphQLClient graphQLClient;
public GraphQLService() {
this.graphQLClient = new GraphQLClient();
}
/**
* 调用 GraphQL 接口
*/
public String fetchData() throws IOException {
// 定义 GraphQL 查询
String query = "query GetUser($id: ID!) { user(id: $id) { name email } }";
// 定义查询变量
Map<String, Object> variables = new HashMap<>();
variables.put("id", "1");
// 发送请求
return graphQLClient.executeQuery(query, variables);
}
/**
* 关闭客户端
*/
public void close() throws IOException {
graphQLClient.close();
}
}
(2)创建控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/graphql")
public class GraphQLController {
private final GraphQLService graphQLService;
@Autowired
public GraphQLController(GraphQLService graphQLService) {
this.graphQLService = graphQLService;
}
@GetMapping("/fetch")
public String fetchData() throws IOException {
return graphQLService.fetchData();
}
}
5. 运行和测试
启动 Spring Boot 应用。
访问
http://localhost:8080/graphql/fetch
,查看 GraphQL 接口的响应结果。
6. 示例 GraphQL 查询
假设 GraphQL 接口的查询如下:
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
对应的变量:
{
"id": "1"
}
响应结果可能为:
{
"data": {
"user": {
"name": "John Doe",
"email": "john.doe@example.com"
}
}
}
7. 总结
通过以上步骤,你可以在 Spring Boot 中使用 HttpClient
调用 GraphQL 接口:
添加
httpclient
和jackson
依赖。创建
GraphQLClient
工具类,用于发送 HTTP 请求。在服务类中调用
GraphQLClient
,处理 GraphQL 查询和响应。通过控制器暴露 API,测试 GraphQL 接口调用。
如果有更复杂的需求(如认证、错误处理等),可以进一步扩展 GraphQLClient
的功能。