在Spring Boot控制器中使用GraphQL API

时间:2018-04-24 12:54:30

标签: java spring-boot graphql

我需要在我的Spring Boot控制器中使用第三方提供的graphQL API,我尝试了here,但得到了400错误。 以下是代码:

@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;
}

当我尝试在Postman中调用相同的URL时,我得到了响应,下面是屏幕截图:

enter image description here

但是当我在我的控制器中尝试它时,我得到以下错误,任何人都可以帮助我如何使用某人的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 个答案:

答案 0 :(得分:0)

我只是尝试通过jersey api调用我的graphQL API,如下所示,我能够得到回复。

@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;
}

有没有其他方法可以进行此调用,或者特别是graphQL方式?