栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Content type ‘application/xml‘ not supported;Could not find acceptable representation

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Content type ‘application/xml‘ not supported;Could not find acceptable representation

学习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 requestEntity = new HttpEntity(user, entityHeaders);

        ResponseEntity  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

  1. pom增加xml的响应支持

    com.fasterxml.jackson.dataformatjackson-dataformat-xml
  2. 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的功能

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936888.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号