Q:

How to use spring restTemplate.exchange directly with json

I use springs restTemplate for sending requests to a rest server. To make things a little bit more complicated I want to send a String which already is a json string directly via restTemplate to the server. Unfortunatly I get http return code 400 (Bad Request)
My code looks similar to
String request = "{\"some\":\"value\"};
RequestEntity<String> request1  = new RequestEntity<String>(request, httpHeaders, HttpMethod.POST, new URI(endpoint));
restTemplate.exchange(request1, String.class);

What am I doing wrong? Do I need a special header?

A:

It depends on what the API expects in request and what it returns in the response. If it accepts and returns json then you need to convert the request string into json object, once done, you can probably use postForEntity method of RestTemplate to return the value, e.g.:
ObjectMapper objectMapper = new ObjectMapper();
String request = "{\"some\":\"value\"}";
Map<String, String> dataMap = objectMapper.readValue(request, Map.class);
ResponseEntity<Map> responseEntity = restTemplate.postForEntity("https://someurl", dataMap, Map.class);
System.out.println("Response : " + responseEntity.getBody());

The above examples uses Jackson to serialise/deserialise the objects (repo here), you can use any json framework to do so.

