简体   繁体   中英

Content type 'null' not supported returned by Spring RESTTemplate getForObject method

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.

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

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