简体   繁体   中英

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?

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, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM