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?
HttpEntity<String>? - JB Nizet