2

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:

enter image description here

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]}}

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.