org.springframework.web.client.RestClientException

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值