简体   繁体   English

如何使用 Java 代码调用 GraphQL 查询/变异

[英]How to call a GraphQL query/mutation with Java code

I know we can use the /graphiql endpoint to test the created or deployed GraphQL API.我知道我们可以使用/graphiql端点来测试创建或部署的 GraphQL API。

在此处输入图片说明

  1. I need to consume a GraphQL API which is already there using a Java code.我需要使用 Java 代码来使用已经存在的 GraphQL API。 How can I do it.我该怎么做。
  2. How can I test a GraphQL end-point using a postman like application, or is it even possible.我如何使用类似应用程序的邮递员测试 GraphQL 端点,或者甚至可能。

Depending on your situation, utilizing Spring RestTemplate might be simplest thing to do.根据您的情况,使用 Spring RestTemplate 可能是最简单的事情。

public class Person {
    @JsonProperty("query")
    public final String query = "mutation($name:String, $gender:String, $age:Int) { updateDetails (name: $name, gender: $gender, age: $age) }";
    @JsonProperty("variables")
    public final Map<String, String> variables;
...
}
...
(new RestTemplate()).postForEntity("http://example.com/graphql", new Person("David", "male", 12));

Could go even simpler by avoiding Spring and using HttpClient, building same JSON document using StringBuilder.通过避免使用 Spring 并使用 HttpClient,使用 StringBuilder 构建相同的 JSON 文档,可以变得更简单。

Alternatively Apollo Andoid can autogenerate client code for you.或者Apollo Andoid可以为您自动生成客户端代码。

An example, to work for me... username and password are wrong :) But, URL is ok...一个例子,为我工作......用户名和密码错误:)但是,URL没问题......

with that, I don't use RestTemplate, any jars, etc..有了这个,我不使用 RestTemplate,任何罐子等等。

private static void test_LivePharma() {
    try {
        URL url = new URL("https://stores-hml.funcionalmais.com/graphql");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");

        String input="{\"query\":\"mutation{createToken(login:\\\"112233\\\",password:\\\"112233\\\"){  token}}\\n\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

Consuming graphql API in your backend code, will require multiple steps such as.在后端代码中使用 graphql API 需要多个步骤,例如。

  1. Defining the schema定义架构
  2. Installing the dependencies安装依赖项
  3. Defining the graphql endpoint定义 graphql 端点
import com.coxautodev.graphql.tools.SchemaParser;
import javax.servlet.annotation.WebServlet;
import graphql.servlet.SimpleGraphQLServlet;


@WebServlet(urlPatterns = "/graphql")
public class GraphQLEndpoint extends SimpleGraphQLServlet {

    public GraphQLEndpoint() {
        super(SchemaParser.newParser()
                .file("schema.graphqls") //parse the schema file created earlier
                .build()
                .makeExecutableSchema());
    }
}

Here is a detailed guide to do the same : Graphql-java-backend-implementation这是执行相同操作的详细指南: Graphql-java-backend-implementation

Yes, it is possible to send the request using postman.是的,可以使用邮递员发送请求。 You can simply copy the schema in the body.您可以简单地复制正文中的架构。 Doing GraphQL request using Postman 使用 Postman 执行 GraphQL 请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM