Error while extracting response for type [class xxx] and content type application/xml;charset=UTF-8 た 入场券 2022-02-23 08:52 193阅读 0赞 强烈推荐一个大神的人工智能的教程:[http://www.captainbed.net/zhanghan][http_www.captainbed.net_zhanghan] ### 【前言】 ### 最近在用restTemplate进行一次http请求时发现了报错(Error while extracting response for type \[class xxx\] and content type application/xml;charset=UTF-8)经过一番尝试后最终解决问题,在此记录一下。 ### 【问题及解决】 ### 一、封装http调用的方法如下: public <T> ResponseEntity<T> postJson(String url, String requestJson, Class<T> responseType) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); HttpEntity<String> entity = new HttpEntity<>(requestJson, headers); ResponseEntity<T> responseEntity; System.out.println(requestJson); responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, responseType); return responseEntity; } 二、提供方为的出参和入参均为json格式; 三、单步进行调试发现报如下错: ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ_size_16_color_FFFFFF_t_70][] 四、在网上查了一些资料并进行了相关验证,对调用方法设置对返回值的格式为json即可解决,相应代码如下: public <T> ResponseEntity<T> postJson(String url, String requestJson, Class<T> responseType) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //设置接收返回值的格式为json List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8); headers.setAccept(mediaTypeList); HttpEntity<String> entity = new HttpEntity<>(requestJson, headers); ResponseEntity<T> responseEntity; System.out.println(requestJson); responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, responseType); return responseEntity; } ### 【小结】 ### 在之前的项目中不用设置接收值的格式也是可以的,之前系统用的SpringBoot版本是1.5.x,现在的项目是将Spring Boot版本升级到2.x;在进行新项目的开发时建议使用比较新的稳定版本的框架,如果是迁移则建议沿用老版本,如果老版本代码向新框架迁移一定要进行全流程的测试,不然可能会有新老版本不兼容而导致的bug。 [http_www.captainbed.net_zhanghan]: http://www.captainbed.net/zhanghan [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ_size_16_color_FFFFFF_t_70]: /images/20220223/c1ca6c641b6e4d819d54dcc0658aa4db.png
还没有评论,来说两句吧...