HttpClientErrorException getResponseBodyAsString()无法将字节解析为字符串

时间:2019-04-17 10:25:06

标签: java spring spring-boot

我从第三方服务器的403 http代码响应中获取响应主体时遇到问题。在2019年4月5日之前,我能够正确地从第三方获取响应主体,但是现在我正在从getResponseBodyAsString检索可能未正确转换为字符串的字节。这是来自org.springframework.web.client包的问题吗?

    @Autowired
    RestClient restClient;
    try{
    //Request via restTemplate
     ResponseEntity<String> responseEntity = restClient.makeClientRequestJson(batch_type.getEndpoint(), HttpMethod.POST, httpHeaders, batch_payload.getRequest(), ProcessorConstants.moduleId);
    } catch (HttpClientErrorException | HttpServerErrorException ex) {
                loggingService.writeLogs("Error From Third Party Request, Message: " + ex.getMessage() + "| Response Body: " + ex.getResponseBodyAsString(), this.getClass(), LoggingEnum.ERROR, BatchConstants.moduleId);
     ...

这是makeClientRequestJson的实现:

public ResponseEntity<String> makeClientRequestJson(String url, HttpMethod httpMethod, HttpHeaders headers, String jsonBody , String moduleId){
    RestTemplate restTemplate = new RestTemplate();

    HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
    loggingService.writeLogs("Third Party Request: " + entity.getBody() + "| url: " + url + " | method: " + httpMethod.toString(), RestClientImpl.class, LoggingEnum.INFO, moduleId);

    ResponseEntity<String> response =  restTemplate.exchange(url, httpMethod, entity, String.class);
    loggingService.writeLogs("Third Party Response: " + response.getBody() + "| url: " + url + " | method: " + httpMethod.toString(), RestClientImpl.class, LoggingEnum.INFO, moduleId);
    return response;
}

问题是当获取ex.getResponseBodyAsString()返回字节数组时,我直接从服务器获取json响应,如:

{
    "code": "403020",
    "transactionID": "1555495478-1409322457-83999786",
    "message": "Account is Level 1"
}

这里是调试代码时得到的样本值: Here is sample value I get when debugging the code

1 个答案:

答案 0 :(得分:0)

我找到了问题的根本原因,这是由于第三方api返回403响应代码,所以我请求将其响应代码更改为400,现在我得到了没有问题的响应正文。但是在我们的产品中,即使客户端返回403响应代码,也不会发生这种情况,但这很奇怪,因为我是在我们的开发服务器上不断导入程序包,所以可以断定这是否是spring.web.client错误。

enter image description here