内容类型' null' Spring RESTTemplate getForObject方法返回不支持

时间:2014-07-01 02:19:22

标签: java rest http spring-mvc

我在Spring MVC控制器中有一个简单的REST方法,其签名为:

  

@RequestMapping(value =“/ person / {personId}”,method = RequestMethod.GET)       public @ResponseBody Object getPerson(@PathVariable(“personId”)String personId){
      ...      }

输出类型为Object,因为此方法返回了几种不同的数据类型。

从Spring MVC应用程序中的测试程序调用时,如下所示:

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(); 
    ...
    }

响应为Content type 'null' not supported,呼叫失败。

有人可以提出建议吗?

当从另一个不使用Spring但发出HTTP GET请求的应用程序中的测试程序调用时,控制器方法被正确调用并起作用。

1 个答案:

答案 0 :(得分:-1)

你可以试试这个:

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);

如果以上操作不起作用,您可以尝试使用Entity方法,例如:

  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);
  }

有很多useful examples here

希望能提供帮助