In a previous blog you learned how to build RESTful web services using Spring, now we are going to show you how build a client to access RESTful web services using Spring’s RestTemplate.
The RestTemplate was introduce in Spring 3.0 and can be used right out the box by including the org.springframework.web jar in your classpath. The RestTemplate provides entry points for the six main HTTP methods:
Http Method | RestTemplate Method |
---|---|
DELETE | delete(String, Object…) |
GET | getForObject(String, Class, Object…) |
HEAD | headForHeaders(String, Object…) |
OPTIONS | optionsForAllow(String, Object…) |
POST | postForLocation(String, Object, Object…) |
PUT | put(String, Object, Object…) |
The method names indicate the HTTP method that they will invoke and the second part of the name indicates what the method will return. The first argument of each method is the URI. The URI can either be a URI template or a normal URI. I am going to show you how to use the RestTemplate to access the dictionary service that was introduced in a previous blog.
GET
To retrieve all the words out of the dictionary we use the following code:
RestTemplate template = new RestTemplate();
WordList wordList = template.getForObject("http://localhost:8080/SpringDictionaryService/bti/dictionary", WordList.class);
To retrieve a word:
Map vars = new HashMap();
vars.put("word", "set");
Word word = template.getForObject("http://localhost:8080/SpringDictionaryService/bti/dictionary/{word}", Word.class, vars);
This method uses a URI template and takes a Map which contains the URI path variables. This same example can be done using a normal URI:
RestTemplate template = new RestTemplate();
Word word = template.getForObject("http://localhost:8080/SpringDictionaryService/bti/dictionary/set", Word.class);
POST
To add a new word to our dictionary we use the following code: