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

标签 java rest http spring-mvc

我在 Spring MVC Controller 中有一个简单的 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(); 
    ...
    }

响应是不支持内容类型'null',调用失败。

谁能告诉我为什么?

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

最佳答案

你可以试试这个:

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 .

希望有所帮助

关于java - Spring RESTTemplate getForObject 方法不支持返回内容类型 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24501590/

相关文章:

java - Android 保存/重写文件到 SD 卡

php - 在 PHP 中发送 HTTP GET 请求(不返回目标 URL 的内容,只是执行它)

java - 删除其他运算符并仅保留文本运算符(TJ,Tj) pdfBox

java - 在 Java 中,是 substring(int k, int y) 还是 substring(int k) 更高效?

javascript - 与 jQuery ajax post 方法相比,fetch 方法未按预期发布

rest - ServiceStack Web 服务的存储转发故障转移解决方案

spring - 无法读取 HTTP 消息 : org. s.HttReadableException : Could not read document: Unrecognized token 'PUT' : was expecting ('true' , 'false' 或 'null')

python - 任何好的 Python HTTP 代理?

http - URI 查询中的 bool 值?

java - 如何解决java文件下载异常?