Exception in thread "main" org.springframework.web.client.HttpClientErrorException$NotAcceptable: 406 Not Acceptable: [no body]
这个bug 是自己在使用RestTemplate发送delete请求携带body 的时候遇到的。
刚开始在网上找原因,有博主说这个因为spring 使用的jdk 的httpclient 发送的请求,所以delete请求的时候,是不能携带请求体的,需要重写一下发送请求的工厂,
参考文章:https://blog.csdn.net/hemingwang0902/article/details/9152431?utm_medium=distribute.pc_relevant.none-task-blog-title-1&spm=1001.2101.3001.4242
https://stackoverflow.com/questions/36899641/resttemplate-delete-with-body
自己在试用了上面两个方法之后,还是报同样的错误。
折腾了将近一天,去看源码,希望找到问题,最后debug 的时候发现ideal 给了一个提醒。
自己尝试更改一下,exchange 方法的返回参数(原来用object接收返回参数,现在用byte[]),结果 方法竟然走通了。通过debug, 只模糊弄清楚一点,等都弄清楚了再写真正的原因。
代码:
public ResponseEntity<byte[]> deleteOrigin(QueryEntity queryEntity){ RestTemplate restTemplate = new RestTemplate(); //认证的账号和密码 String authentication = queryEntity.getUsername() + ":" + queryEntity.getPassword(); HttpHeaders headers = new HttpHeaders(); //在请求头信息中携带Basic认证信息(这里才是实际Basic认证传递用户名密码的方式) headers.set("authorization", "Basic " + Base64.getEncoder().encodeToString(authentication.getBytes())); MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM)); restTemplate.getMessageConverters().add(mappingJackson2HttpMessageConverter); //设置编码格式 MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); String url = "http://" + queryEntity.getIp() + ":" + queryEntity.getPort() + queryEntity.getParam(); return restTemplate.exchange(url, HttpMethod.DELETE, new HttpEntity<Object>(queryEntity.getBody(), headers), byte[].class); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)