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<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

  1. pom增加xml的响应支持

    <dependency><groupId>com.fasterxml.jackson.dataformat</groupId><artifactId>jackson-dataformat-xml</artifactId></dependency>
  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的功能

当出现"Content type 'application/octet-stream' not supported"的异常时,这意味着请求的Content-Type类型不被服务器支持。在HTTP请求头中,Content-Type标头指定了请求发送的数据类型,如果服务器无法处理该类型的数据,就会出现这个异常。 要解决这个问题,有几个思路可以尝试。首先,确认服务器端是否支持该Content-Type类型,如果不支持,需要添加对该类型的支持。其次,检查请求中的Content-Type标头是否正确设置为'application/octet-stream',如果不正确,可以尝试将其更改为服务器支持的正确类型。最后,还可以检查是否有其他配置或代码问题导致服务器无法处理特定类型的请求。 总结起来,解决"Content type 'application/octet-stream' not supported"异常的方法包括确认服务器端是否支持该Content-Type类型、检查请求中的Content-Type标头是否正确设置,并检查其他可能导致异常的配置或代码问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【error】 Content typeapplication/octet-stream‘ not supported app端调接口时报错,自己调用时不...](https://blog.youkuaiyun.com/qq_43622777/article/details/130412718)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值