2
votes

Is it possible to pass raw JSON to a Rest API using the Spring RestTemplate?

I am attempting the following:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
String jsonText = // raw JSON
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(jsonText, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);

When I invoke this request, I get a HTTP 400 error response, meaning bad request. However, all headers and the JSON body are identical as that submitted using a HTTP client I have.

In contrast, the following works fine when I create the MyRequest object and set it on the HttpEntity:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
    httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
    restTemplate.setMessageConverters(httpMessageConverters);
    MyRequest myRequest = new MyRequest();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<?> entity = new HttpEntity<Object>(myRequest, httpHeaders);
    restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);

Therefore, I am wondering how I can invoke my REST API using raw JSON in String format?

1
Have you tried not setting the message converters, since you don't want your message to be converted to anything? Also, why not make it a HttpEntity<String>? - JB Nizet

1 Answers

1
votes

This is Method

            String url = String.format("https://SITE");
            RestTemplate template = new RestTemplate();
            template.getMessageConverters().add(new StringHttpMessageConverter());

            String valor ="{\"cmd\":\"123\", \"includeImei\":\"true\"}";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authenticate", "TOKEN");


            HttpEntity<String> entity = new HttpEntity<String>(valor, headers);
            URI valoresdevueltos = template.postForLocation(url, entity);