kri*_*293 2 java resttemplate spring-boot graphql-java
目前我们想使用 resttemplate 在 springboot 应用程序中使用一个 graphQL 端点
但是,当我们使用以下查询发出 POST 请求时,我们总是收到相同的错误 {"errors":[{"message":"No query string was present"}]}
下面是片段,我们要运行,
@Test
public void testSwoop(){
RestTemplate restTemplate = restTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer *************");
headers.add("content-type", "application/graphql");
String query1 = "{\n" +
" \"query\": query {\n" +
" \"locationTypes\": {\n" +
" \"edges\": \n" +
" {\n" +
" \"node\": \n" +
" {\n" +
" \"name\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String URL = "https://staging.joinswoop.com/graphql";
ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
System.out.println("The response================="+response);
}
Run Code Online (Sandbox Code Playgroud)
但是从邮递员那里,我们在使用端点时没有任何问题,并且我们得到了很好的响应

有人可以帮助我们将我们引向正确的资源吗
您将内容类型标头设置为“application/graphql”,但是您正在发送 JSON 作为数据。两种可能有效的解决方案:
发送 JSON:
将内容类型设置为“application/json”并发送一个 JSON 格式的查询:
@Test
public void testSwoop(){
RestTemplate restTemplate = restTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer *************");
headers.add("content-type", "application/json"); // just modified graphql into json
String query1 = "{\n" +
" \"query\": query {\n" +
" \"locationTypes\": {\n" +
" \"edges\": \n" +
" {\n" +
" \"node\": \n" +
" {\n" +
" \"name\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String URL = "https://staging.joinswoop.com/graphql";
ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
System.out.println("The response================="+response);
}
Run Code Online (Sandbox Code Playgroud)
发送 GraphQL 查询:
如果您的服务器支持(应该),请将内容类型设置为“application/graphql”,并以字符串形式发送真实的 graphql 查询。
@Test
public void testSwoop(){
RestTemplate restTemplate = restTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer *************");
headers.add("content-type", "application/graphql"); // maintain graphql
// query is a grapql query wrapped into a String
String query1 = "{\n" +
" locationTypes: {\n" +
" edges: \n" +
" {\n" +
" node: \n" +
" {\n" +
" name\n" +
" }\n" +
" }\n" +
" }\n" +
" }";
String URL = "https://staging.joinswoop.com/graphql";
ResponseEntity<String> response = restTemplate.postForEntity(URL, new HttpEntity<>(query1, headers), String.class);
System.out.println("The response================="+response);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5542 次 |
| 最近记录: |