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

强颜欢笑 提交于 2021-01-27 14:11:40

问题


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?


回答1:


Try this,

private static HttpEntity<?> getHeaders(){
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
    return new HttpEntity<>(headers);
}

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

        String requestJson = "{ \"meta\": \"NJ\", \"name\": \"US\" }";
        Object lado = restTemplate.getForObject("http://ec2-URL.com:5000/TL/data?requestJson= {requestJson}", Object.class,requestJson, getHeaders());

    } catch (Exception exc) {
        logger.error("[WebServiceCallerUtil] Exception while calling . {} ", exc.getMessage());
    }
    return " ";
}

--

HTTP GET doesn't have request body. So here am explaining how to send the data through reqeustparam in GET method.



来源:https://stackoverflow.com/questions/56544432/how-to-send-body-as-a-json-in-resttemplate-to-get-data-from-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!