You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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.

1. Calling a GraphQL API with Java

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:

  1. Add the Maven dependency:
<dependency>
    <groupId>com.graphql-java</groupId>
    <artifactId>graphql-java-client</artifactId>
    <version>19.0</version>
</dependency>
  1. 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; }
}
  1. 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() + ")");
    }
}
2. Testing GraphQL Endpoints with Postman-like Tools

Absolutely! Tools like Postman, Insomnia, and Altair work great for testing GraphQL endpoints—here's how to use the most popular ones:

Using Postman

  1. Open Postman and create a new POST request.
  2. Enter your GraphQL endpoint URL (e.g., http://your-api-domain/graphql).
  3. Go to the Body tab:
    • Select Raw as the body type.
    • Choose JSON from the dropdown menu.
  4. Paste your GraphQL query/mutation in the JSON body (wrap it in a query field):
    {
      "query": "query { getUser(id: 1) { name email } }"
    }
    
  5. Add any required headers (like Authorization: Bearer YOUR_TOKEN) in the Headers tab.
  6. 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:

  1. Create a new GraphQL request in Insomnia.
  2. Enter your endpoint URL—Insomnia will automatically fetch the API schema (if the endpoint allows introspection).
  3. Use the built-in query editor to write your query/mutation with auto-completion (no need to wrap it in JSON!).
  4. Add headers in the Headers tab if needed.
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:10:06