【问题标题】:Consuming GraphQL API in Spring Boot controller在 Spring Boot 控制器中使用 GraphQL API
【发布时间】:2018-10-04 17:57:17
【问题描述】:

我需要在我的 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 时,我得到了响应,下面是截图:

但是当我在我的控制器中尝试它时,我得到以下错误,谁能帮助我如何使用某人的 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]}}

【问题讨论】:

    标签: java spring-boot graphql


    【解决方案1】:

    我刚刚尝试通过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 方式?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2021-05-02
      • 2016-09-19
      • 2021-02-08
      • 2016-09-17
      • 2019-01-18
      • 2019-02-20
      相关资源
      最近更新 更多