Implementing PUT REST requests when using Spring RestTemplate

Spring’s RestTemplate.put(…) method returns a void. Why is this a bother? One reason is to capture PUT response information and make logical decisions based on that data.

As it turns out, The RestTemplate’s exchange method can be used to implement the PUT request using the following snippet. It’s not complete code but enough to the point where it should be self explanatory


public boolean putIndex(String id) throws Exception {
 final String endpoint = endpoint("index/{id}");

HttpHeaders requestHeaders = new HttpHeaders();
 List <MediaType> mediaTypeList = new ArrayList<MediaType>();
 mediaTypeList.add(MediaType.APPLICATION_JSON);
 requestHeaders.setAccept(mediaTypeList);
 requestHeaders.setContentType(MediaType.APPLICATION_JSON);
 HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

 // Create the HTTP PUT request,
 ResponseEntity<Object> response = operations.exchange(endpoint, HttpMethod.PUT, requestEntity, null, id);
 if (response == null) {
 return false;
 }
 return HttpStatus.CREATED.equals(response.getStatusCode());
 }

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s