学习Spring4.x企业应用开发实战第17章Spring MVC时,使用RestTemplate编写调用handle51()客户端程序。
RestTemplate restTemplate = buildRestTemplate();
User user = new User();
user.setUserName("tom");
user.setPassword("1234");
user.setRealName("汤姆");
HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(MediaType.valueOf("application/xml;UTF-8"));
entityHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
HttpEntity<User> requestEntity = new HttpEntity<User>(user, entityHeaders);
ResponseEntity<User> responseEntity =restTemplate.exchange(
"http://localhost:8080/chapter17_war/user/handle51",
HttpMethod.POST,requestEntity, User.class);
服务端启动Web服务,运行testhandle51()测试方法。 没有进入服务端方法,报错Content type 'application/xml' not supported
于是猜想: 肯定是Tomcat帮我们做了解析, 一解析的话, 肯定得读流啊, 所以当我获取到流的时候, 流已经被处理掉了, 所以我获取不到原始的请求正文了.
解决办法:链接参考spring-boot(三)响应返回json和xml
-
pom增加xml的响应支持
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
-
User类增加xml注解支持@XmlRootElement
2、使用Json格式请求、响应消息
将请求报文头的Content-Type及Accpt属性更改为application/json。
这里有个坑,书本源代码请求url为
http://localhost:8080/chapter17_war/user/handle51.html
可以进到调用方法中,但服务端报错Could not find acceptable representation;
去掉.html后缀或者改为.json,测试方法通过
另附其他博客的解释:
当用户请求 /handle51.html 时,spring会查找/login对应的控制器,并得到其返回的文档类型为application/json, 然后判断它与后缀名.html文档类型是否匹配,如果不匹配,就报HttpMediaTypeNotAcceptableException了。
其实它的初衷是好的,它是想实现访问/user.json时返回JSON数据,访问/user.html返回HTML, 访问/user.xml则返回XML的功能