如何用Java代码调用GraphQL查询/突变?类Postman工具能否测试GraphQL端点?
Great question! Let's cover both parts of your query in detail—first how to call a GraphQL API using Java, then how to test it with Postman-like tools.
GraphQL APIs typically accept POST requests with a JSON body containing your query or mutation. There are a few common ways to implement this in Java:
Option 1: Native Java (No Third-Party Libraries)
If you want to avoid adding dependencies, you can use HttpURLConnection directly for simple requests:
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class NativeGraphQLClient { public static void main(String[] args) throws Exception { // Replace with your API endpoint String graphqlEndpoint = "http://your-api-domain/graphql"; // Your GraphQL query (wrap in JSON for POST body) String queryPayload = "{ \"query\": \"query { getUser(id: 1) { name email } }\" }"; URL url = new URL(graphqlEndpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Configure request conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); // Send the request body try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.writeBytes(queryPayload); wr.flush(); } // Read and print the response try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println("GraphQL Response:\n" + response.toString()); } } }
This works for basic use cases, but you'll need to handle error cases and JSON parsing manually.
Option 2: Spring WebClient (For Reactive Spring Apps)
If you're using Spring Boot, WebClient is a clean, reactive way to call APIs:
import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; public class SpringGraphQLClient { public static void main(String[] args) { WebClient webClient = WebClient.create("http://your-api-domain/graphql"); String graphQLQuery = "query { getUser(id: 1) { name email } }"; String requestBody = "{ \"query\": \"" + graphQLQuery.replace("\"", "\\\"") + "\" }"; Mono<String> responseMono = webClient.post() .header("Content-Type", "application/json") // Add auth headers here if needed (e.g., .header("Authorization", "Bearer YOUR_TOKEN")) .bodyValue(requestBody) .retrieve() .bodyToMono(String.class); // Subscribe to the reactive response responseMono.subscribe( response -> System.out.println("Response:\n" + response), error -> System.err.println("Error calling API: " + error.getMessage()) ); } }
Option 3: Type-Safe GraphQL Java Client
For more complex projects, use the GraphQL Java Client to get type-safe responses and avoid manual JSON parsing:
- Add the Maven dependency:
<dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-java-client</artifactId> <version>19.0</version> </dependency>
- Define a POJO matching your GraphQL response:
public class User { private String name; private String email; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
- Make the type-safe call:
import com.graphqljava.client.GraphQLClient; import com.graphqljava.client.Request; import com.graphqljava.client.Response; public class TypeSafeGraphQLClient { public static void main(String[] args) { GraphQLClient client = GraphQLClient.create("http://your-api-domain/graphql"); Request request = Request.newRequest() .query("query { getUser(id: 1) { name email } }") .build(); Response response = client.send(request); User user = response.get("getUser", User.class); System.out.println("Fetched User: " + user.getName() + " (" + user.getEmail() + ")"); } }
Absolutely! Tools like Postman, Insomnia, and Altair work great for testing GraphQL endpoints—here's how to use the most popular ones:
Using Postman
- Open Postman and create a new POST request.
- Enter your GraphQL endpoint URL (e.g.,
http://your-api-domain/graphql). - Go to the Body tab:
- Select Raw as the body type.
- Choose JSON from the dropdown menu.
- Paste your GraphQL query/mutation in the JSON body (wrap it in a
queryfield):{ "query": "query { getUser(id: 1) { name email } }" } - Add any required headers (like
Authorization: Bearer YOUR_TOKEN) in the Headers tab. - Click Send—you'll see the JSON response in the lower panel.
Using Insomnia (GraphQL-Optimized)
Insomnia has native GraphQL support that makes testing easier:
- Create a new GraphQL request in Insomnia.
- Enter your endpoint URL—Insomnia will automatically fetch the API schema (if the endpoint allows introspection).
- Use the built-in query editor to write your query/mutation with auto-completion (no need to wrap it in JSON!).
- Add headers in the Headers tab if needed.
- Click Send to view formatted responses, including syntax highlighting for JSON.
Bonus: Built-in /graphiql Endpoint
You mentioned you already know about the /graphiql endpoint—this is a great interactive tool for quick testing, but Postman-like tools are better for saving requests, sharing with your team, and setting up automated test suites.
内容的提问来源于stack exchange,提问作者prime

