POST request via RestTemplate in JSON POST request via RestTemplate in JSON java java

POST request via RestTemplate in JSON


This technique worked for me:

HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);ResponseEntity<String> response = restTemplate.put(url, entity);

I hope this helps


I ran across this problem when attempting to debug a REST endpoint. Here is a basic example using Spring's RestTemplate class to make a POST request that I used. It took me quite a bit of a long time to piece together code from different places to get a working version.

RestTemplate restTemplate = new RestTemplate();String url = "endpoint url";String requestJson = "{\"queriedQuestion\":\"Is there pain in your hand?\"}";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);String answer = restTemplate.postForObject(url, entity, String.class);System.out.println(answer);

The particular JSON parser my rest endpoint was using needed double quotes around field names so that's why I've escaped the double quotes in my requestJson String.


I've been using rest template with JSONObjects as follow:

// create request bodyJSONObject request = new JSONObject();request.put("username", name);request.put("password", password);// set headersHttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> entity = new HttpEntity<String>(request.toString(), headers);// send request and parse resultResponseEntity<String> loginResponse = restTemplate  .exchange(urlString, HttpMethod.POST, entity, String.class);if (loginResponse.getStatusCode() == HttpStatus.OK) {  JSONObject userJson = new JSONObject(loginResponse.getBody());} else if (loginResponse.getStatusCode() == HttpStatus.UNAUTHORIZED) {  // nono... bad credentials}