简体   繁体   中英

How to call GraphQL api from java HttpClient with query and variables?

I'm trying to call GraphQL API post endpoint with query and variables. Query and variables both add as JSON object. But return "Invalid request".

I've read through numerous questions here on Stack overflow, but I did not encounter the problem I'm having.

Java sample

public class main3 {
    public static void main(String[] args) throws IOException {
        String line, queryString, url;
        url = "https://search-sandbox.sample.com/graphql";
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;

        client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);

        httpPost.addHeader("Authorization", "Basic VG91**");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-Type", "application/json");

          try {
            
                String query = "query getPropertiesByIds($SearchCriteriaByIds: SearchCriteriaByIdsInput) {\n"
                + "  getPropertiesByIds(searchCriteriaByIds: $SearchCriteriaByIds) {\n"
                + "  properties {\n"
                + "      propertyId\n"
                + "    }\n"
                + "  }\n"
                + "}";
        
                String variable = "{\n"
                + " \"SearchCriteriaByIds\": {\n"
                + "     \"propertyIds\": [\n"
                + "         134388,\n"
                + "         424023,\n"
                + "         134388,\n"
                + "         22549064\n"
                + "     ]\n"
                + " }\n"
                + "}";
            
            Map<String, Object> variables = new HashMap<>();
            
            variables.put("query", query);
            variables.put("variables", variable);
            
            JSONObject jsonobj; 
            jsonobj = new JSONObject(variables);


            StringEntity entity = new StringEntity(jsonobj.toString());
            httpPost.setEntity(entity);

            
            response = client.execute(httpPost);

            BufferedReader bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuilder builder = new StringBuilder();

            while ((line = bufReader.readLine()) != null) {
                builder.append(line);
                builder.append(System.lineSeparator());
            }

            System.out.println(builder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Return error code -

{"errorCode":1006,"errorMessage":"Invalid request.","details":null}

Please assist me to find out the issues.

Variable must be json string but not in "".

and take request as json like below Graphql Request

String str= { "query": "query branchLocator ($filterCriteria: [FilterCriteria],$sortBy: SortBy){branchLocator (filterCriteria: $filterCriteria, offset: 0, limit: 20, sortBy: $sortBy) { postalCode latitude longitude addId1 addName1 addAddress1 addCity1 distance1 addId2 addName2 addAddress2 addCity2 distance2 addId3 addName3 addAddress3 addCity3 distance3 addId4 addName4 addAddress4 addCity4 distance4 addId5 addName5 addAddress5 addCity5 distance5 addId6 addName6 addAddress6 addCity6 distance6}}", "variables": {"filterCriteria":[{"key":"postalCode","filterInput":{"filterType":"eq","filterValues":["123456"]}}]}

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM