How to send body as a Json in RestTemplate to get data from API

Viewed 3854

Hi I am trying to get data from the Rest caller to get data from the API my api end point support the get method with the json body as a request when I use curl it is working my curl command is :

curl -X GET http://ec2-URL.com:5000/TL/data  -H 'Content-Type: application/json'  -d '{ "meta": "NJ", "name": "US"}'

And My Spring code is this:

public String getData() {
        RestTemplate restTemplate = new RestTemplate();
        try {

            String requestJson = "{ \"meta\": \"NJ\", \"name\": \"US\" }";
            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");
            HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<?> lado = restTemplate.exchange("http://ec2-URL.com:5000/TL/data", HttpMethod.GET, entity, Object.class);
        } catch (Exception exc) {
            logger.error("[WebServiceCallerUtil] Exception while calling . {} ", exc.getMessage());
        }
        return " ";
    }

I am getting bad request everytime am I dong any wrong.. I know its very easy but.. I tried to use Map also like this :

MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("meta", "NJ");
            map.add("name", US);
HttpEntity<?> entity = new HttpEntity<>(map, httpHeaders);

What is my mistake? How to send json body in the get method?

0 Answers
Related