Spring服务IdentificationResponse无法转ResponseEntity错误如何解决
报错问题解决方案
错误根因
该类转换异常是返回值类型不匹配导致的:
- 你
createIdentification方法声明的返回值类型为ResponseEntity<IdentificationResponse> HandleResponse.handleResponse方法在HTTP状态码为200/201时,返回的是response.getBody(),也就是IdentificationResponse类型的实例,并非ResponseEntity对象,直接返回就会触发类型转换异常。
额外代码笔误修复
你当前代码里存在一处编译错误:
原代码写的HttpEntity<IdentificationRequest> requestHttpEntity = new HttpEntity<>(IdentificationRequest);,构造HttpEntity时误传入了类名,应该改为你已经实例化的对象 identificationRequest,正确写法为:HttpEntity<IdentificationRequest> requestHttpEntity = new HttpEntity<>(identificationRequest);
两种修复方案
你可以根据业务需求二选一:
方案1:保留方法返回ResponseEntity的定义
修改handleResponse工具方法,直接返回ResponseEntity对象:
public static <T> ResponseEntity<T> handleResponse(ResponseEntity<T> response) { HttpStatus code = response.getStatusCode(); if (code == HttpStatus.OK || code == HttpStatus.CREATED || code == HttpStatus.NO_CONTENT) { return response; } else if (code == HttpStatus.BAD_REQUEST) { throw new BadRequestException("BadRequest Exception occured while requesting! Exception details: " + response.getBody()); } else if (code == HttpStatus.UNAUTHORIZED) { throw new UnauthorizedException("Unauthorized Exception occured while requesting! Exception details: " + response.getBody()); } else { throw new HttpClientException("Exception occured! Exception details: " + response.getBody(), code.value()); } }
修改后原有createIdentification方法的返回逻辑无需调整,类型完全匹配。
方案2:修改业务方法返回值类型
如果上层只需要响应体内容,不需要状态码、响应头等信息,可以直接修改createIdentification的返回值类型:
@Override public IdentificationResponse createIdentification(Request request) { IdentificationRequest identificationRequest = new IdentificationRequest(serviceConfig.getIssuerKey(), serviceConfig.getSecureKey()); identificationRequest.setOperation(ClientConstants.CREATE_IDENTIFICATION_ADD); HttpEntity<IdentificationRequest> requestHttpEntity = new HttpEntity<>(identificationRequest); ResponseEntity<IdentificationResponse> response = restTemplate.exchange(platform, HttpMethod.POST, requestHttpEntity, IdentificationResponse.class); return HandleResponse.handleResponse(response); }
内容的提问来源于stack exchange,提问作者john deltana
相关产品推荐
相关产品推荐

