I need to consume graphQL API provided by third party inside my Spring Boot controller, I tried as mentioned here but getting 400 error. Below is the code:
@SuppressWarnings("unchecked")
@RequestMapping(value = "/graphQLTest")
public ResponseEntity<?> testGraphQL() throws JsonProcessingException {
CloseableHttpClient client= null;
CloseableHttpResponse response= null;
client= HttpClients.createDefault();
HttpPost httpPost= new HttpPost("http://172.30.66.149:3000/graphql");
httpPost.addHeader("Accept","application/json");
try {
StringEntity entity= new StringEntity("{\"query\":\"{hello}\"}");
httpPost.setEntity(entity);
response= client.execute(httpPost);
System.out.println("response: "+response);
}
catch(UnsupportedEncodingException e){
e.printStackTrace();
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
return null;
}
When I tried to call same URL in Postman I get the response, below is the screenshot:
But when I try it in my controller, I get below error, Can anyone help me out how can I consume someone's GraphQL API .
Error: HttpResponseProxy{HTTP/1.1 400 Bad Request [X-Powered-By: Express, Content-Type: application/json; charset=utf-8, Content-Length: 53, ETag: W/"35-1vperDe+r7EpHry/i+J3wg", Date: Tue, 24 Apr 2018 12:32:52 GMT, Connection: keep-alive] ResponseEntityProxy{[Content-Type: application/json; charset=utf-8,Content-Length: 53,Chunked: false]}}
I just tried to call my graphQL API through jersey api
as below and I was able to get the response.
@SuppressWarnings("unchecked")
@RequestMapping(value = "/graphQLTest")
public ResponseEntity<?> testGraphQL() throws JsonProcessingException {
JSONObject jsonObj = new JSONObject();
jsonObj.put("query", "{\n" +
" hello\n" +
"}");
Client client = Client.create();
String URL = "http://172.30.66.149:3000";
WebResource webResource = client.resource(URL);
ClientResponse response = webResource.type("application/json").accept("application/json").post(ClientResponse.class, jsonObj.toString());
String output = response.getEntity(String.class);
System.out.println(output);
return null;
}
Is there any alternate way to make this call, or specifically graphQL way?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.