piet
piet

Reputation: 406

How to avoid string escape in resttemplate postForObject

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?

Upvotes: 4

Views: 3877

Answers (2)

Bobo
Bobo

Reputation: 21

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);

Upvotes: 2

piet
piet

Reputation: 406

So, after spending much time on research i think it is the best way to use JSONObject for that. My solution looks like:

...
final JSONObject jsonobject = new JSONObject(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<>(jsonobject.toString(), headers);

restTemplate.postForObject("http://localhost:8080/data/bulk", entity, Void.class);
...

This works for me and solves my problem with String escaping.

Upvotes: 1

Related Questions