[英]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。
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 需要多个步骤,例如。
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.