org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.leyou.httpdemo.pojo.User] and content type [text/html;charset=UTF-8]
在测试使用restTemplate时,出现了一个错误
服务的生产者:
@Controller
@RequestMapping("user")
public class HelloController {
// @Autowired
// private DataSource dataSource;
@Autowired
private UserService userService;
@GetMapping("{id}")//这是对外提供的服务
public String hello(@PathVariable("id") Long id,Model model){
//System.out.println("hello method is running");
User user = userService.findUserByPrimaryKey(id);
List<User> users = new ArrayList<>();
users.add(user);
model.addAttribute("users", users);
return "users";
}
}
服务的消费者:
@RunWith(SpringRunner.class)
@SpringBootTest
public class HttpDemoApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Test
public void httpGet() {
User user = restTemplate.getForObject("http://localhost:8088/user/9", User.class);
System.out.println("user = " + user);
}
}
结果出现如下错误:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.leyou.httpdemo.pojo.User] and content type [text/html;charset=UTF-8]
原因是: 我在服务的生产者中使用了Thymeleaf模板,调用hello()方法时,return “users”,返回给服务的消费者时,应该是"users"字符串,所以抛出Could not extract response无法提取响应.
解决方法: 为hello()方法添加上@ResponseBody,并且修改返回值类型。因为加上@ResponseBody,return XXX时不会去找Thymeleaf中的XXX.html页面,而是直接返回该类型给请求方,这样服务的消费者就能够接受该响应,将其转化成响应的对象.
@GetMapping("{id}")
@ResponseBody
public User hello(@PathVariable("id") Long id,Model model){
//System.out.println("hello method is running");
User user = userService.findUserByPrimaryKey(id);
List<User> users = new ArrayList<>();
users.add(user);
model.addAttribute("users", users);
return user;
}