3

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?

sudar
  • 1,446
  • 2
  • 14
  • 26
  • 1
    It doesn't make sense to send any request body with GET requests. HTTP servers are allowed to ignore them. – Sotirios Delimanolis Jun 11 '19 at 14:23
  • @SotiriosDelimanolis If so why it is working if I am trying form the postman and the curl command.. – sudar Jun 11 '19 at 14:25
  • I don't know how your server is implemented, so I can't answer that. What else does the 400 Bad Request say? Does it contain an error message explaining what part of the request is wrong? – Sotirios Delimanolis Jun 11 '19 at 14:28
  • 1
    GET requests should pass data in form of request parameters, query strings or header information. It does not make sense, to use the body for get requests. Spring’s RestTemplate did think the same and did not send the data along with in the request, because GET requests should have request parameters not body entities. Have a look at this blog post hope it will help you. https://cleanprogrammer.net/making-get-request-with-body-using-spring-resttemplate/ – Devilluminati Jun 11 '19 at 14:37

0 Answers0