Error while extracting response for type [class xxx] and content type application/xml;charset=UTF-8

强烈推荐一个大神的人工智能的教程: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格式;

        三、单步进行调试发现报如下错:

        四、在网上查了一些资料并进行了相关验证,对调用方法设置对返回值的格式为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。

发布了291 篇原创文章 · 获赞 2657 · 访问量 536万+

猜你喜欢

转载自blog.csdn.net/u012829124/article/details/89072111
今日推荐