Having a client should send plain json string to a RESTful service:
...
final Gson gson = new GsonBuilder().create();
final String payload = gson.toJson(data);
final RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
final HttpEntity<String> entity = new HttpEntity<>(payload, headers);
restTemplate.postForObject("http://localhost:8080/data/bulk", entity, Void.class);
...
The produced json by GSON looks like:
{ "id" : { "poid" : "5b70cabhsdf66d99sdakfj37e45" } ... }
The REST service now is receiving the request:
@RequestMapping(value = "/data/bulk", method = RequestMethod.POST)
public ResponseEntity<Void> bulkInbound(@RequestBody final String bulkjson) {
But the string in request body which should be exactly the same as the produced json looks like:
{ \"id\" : { \"poid\" : \"5b70cabhsdf66d99sdakfj37e45\" } ... }
So the string in the body is escaped which makes some problems. Sending the same json string via POSTMAN ist works like a charme without escaping. How can i tell resttemplate in my client not to escape my string?
For whoever still encounters this... took me hours to find it:
Adding StringHttpMessageConverter as the first converter fixed the escaping issue and still using GSON for serializing (ie gson.toJson(data)). With this change the JSON was posted with double-quotes unescaped.
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new StringHttpMessageConverter());
converters.add(new GsonHttpMessageConverter());
restTemplate.setMessageConverters(converters);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With