Spring RestTemplate - HttpClientErrorException.getResponseBodyAsString() 返回无法解析的值

问题描述 投票:0回答:1

我正在使用 Spring RestTemplate,并且在使用

HttpClientErrorException
捕获
postForEntity()
时遇到问题。 Exception 的
getResponseBodyAsString()
方法在
String
值中获取一些随机字符。

try{
    HttpEntity<Object> reqEntity = new HttpEntity<Object>(objPayload, headers);
    ResponseEntity<Object> resEntity = restTemplate.postForEntity(url, reqEntity, Object.class);
} catch(HttpStatusCodeException he) {
    log.error("Exception Status: {} -  {}", he.getStatusCode(), he.getStatusText());
    log.error("Exception - header {} ", he.getResponseHeaders());
    log.error("\n Exception - message  {} ", he.getResponseBodyAsString());
}

异常消息:

2024-02-01 14:48:28.801 ERROR [http-nio-8888-exec-2][APIController:318] Exception Status: 400 BAD_REQUEST -  Bad Request
<br/>
2024-02-01 14:48:28.802 ERROR [http-nio-8888-exec-2][APIController:319] Exception - header : [X-API-Mode:"Sandbox", Content-Encoding:"gzip", Content-Type:"application/json", Content-Length:"192", Server:"server-Gateway", Date:"Thu, 01 Feb 2024 19:48:28 GMT", Connection:"close", Server-Timing:"cdn-cache; desc=MISS", "edge; dur=25", "origin; dur=753", "ak_p; desc="1706816908113_1611090436_118439255_77820_5277_40_0_-";dur=1"]

返回的

String
带有奇怪的字符:

2024-02-01 14:48:28.802 ERROR [http-nio-8888-exec-2][APIController:320] 
Exception - message    �       ��
        �@F_�2��ҝd� �hQ���\k�f`�&��������F�m@��Y�E!��-a�m�4Y��<�]��jݩ��3���A�Q(�i
        ˪:�6��Rֱ<^�ZV����1+�'���w-#Ӳ�n0V��p�Ͳq����wg,�ǀ���u   ��I�  `À/�c����$u^� 

使用 Postman 向同一端点发出请求,我无法重现该问题:

{
    "transactionId": "063dfe4c-07c3-4dc1-b495-e0ae41520",
    "errors": [
        {
            "code": "INVALID.INPUT.EXCEPTION",
            "message": "Invalid field value"
        }
    ]
}
spring resttemplate
1个回答
0
投票

日志中的

Content-Encoding
表示
gzip
,这意味着您正在调用的API正在返回以gzip格式压缩的响应,Postman可以将其解压缩并显示为JSON。然而,默认的
RestTemplate
缺乏解压缩 JSON 的能力,因此日志中会出现奇怪的字符。您可以自定义
RestTemplate
bean 以在内部使用
Apache HttpClient
,它可以处理 gzip 压缩响应。

Bean定义:

import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                HttpClientBuilder.create().build()
        );
        RestTemplate restTemplate = restTemplateBuilder.build();
        restTemplate.setRequestFactory(requestFactory);

        return restTemplate;
    }
}

额外依赖:

implementation group: 'org.apache.httpcomponents.client5', name: 'httpclient5', version: '5.3.1'
© www.soinside.com 2019 - 2024. All rights reserved.