Reputation: 2243
I have a simple REST method in a Spring MVC controller as follows which has a signature of:
@RequestMapping(value="/person/{personId}", method=RequestMethod.GET) public @ResponseBody Object getPerson(@PathVariable("personId") String personId) {
... }
The output is type Object
because several different data types are returned from this method.
When called from a test program within the Spring MVC application, as follows:
private static void getPerson() {
logger.info(Rest.class.getName() + ".getPerson() method called.");
RestTemplate restTemplate = new RestTemplate();
Person person = restTemplate.getForObject("http://localhost:8080/Library/rest/person/1", Person.class);
ObjectMapper responseMapper = new ObjectMapper();
...
}
The response is Content type 'null' not supported
and the call fails.
Can anyone advise why?
When called from a test program in another application which doesn't use Spring but which makes HTTP GET requests, the controller method is called properly and works.
Upvotes: 3
Views: 18135
Reputation: 30995
You can try this:
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setReadTimeout(VERSION_CHECK_READ_TIMEOUT);
RestTemplate template = new RestTemplate(requestFactory);
Person person = restTemplate.getForObject("http://localhost:8080/Library/rest/person/1", Person.class);
If above doesn't work you can try using a Entity
approach like:
RestTemplate restTemplate = new RestTemplate();
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.APPLICATION_XML); // Set what you need
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<Person> entity = new HttpEntity<Person>(headers);
// Send the request as GET
try {
ResponseEntity<PersonList> result = restTemplate.exchange("http://localhost:8080/Library/rest/person/1", HttpMethod.GET, entity, PersonList.class);
// Add to model
model.addAttribute("persons", result.getBody().getData());
} catch (Exception e) {
logger.error(e);
}
There are many useful examples here.
Hope to help
Upvotes: -1