簡體   English   中英

出現錯誤時如何使用RestTemplate讀取正文?

[英]how to read body using RestTemplate in case of an error?

我正在使用RestTemplate與一種REST服務通信,我使用

     restTemplate.postForEntity(uri, request, MyResponse.class);
 } catch (HttpClientErrorException e)

但是,當出現錯誤(4xx或5xx)時,REST服務在主體中以JSON形式返回描述,但是HttpClientErrorException.getResponseBodyAsString()返回null。 RestTemplate(如果我嘗試將響應檢索為String),則不會返回任何內容。

出現錯誤時如何取回屍體?

您可以通過ResponseErrorHandler訪問響應以獲取錯誤。 需要使用setErrorHandler方法為RestTemplate設置ResponseErrorHandler

ResponseErrorHandler通過兩種方法提供響應

boolean hasError(ClientHttpResponse response)拋出IOException;

void handleError(ClientHttpResponse response)引發IOException;

問題已被識別,在此處進行了描述https://jira.spring.io/browse/SPR-16781?focusedCommentId=159473&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-159473和此處https: //jira.spring.io/browse/SPR-9367

您需要使用其他http庫,例如Apache HttpClient(不是JDK的默認庫)。

添加到您的項目:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

並使用以下命令配置RestTemplate:

restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());

您可以根據需要使用ResponseErrorHandler ,但這不是必需的。

現在,響應主體(即使處於錯誤情況下)也存儲在HttpClientErrorException中 ,並使用getResponseBodyAsString()方法讀取它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM