当响应中出现“>”和“ <”符号时,restTemplate.exchange方法给出错误

时间:2019-04-03 04:28:04

标签: java spring http resttemplate

我正在编写一个函数,以向一些REST API发送POST请求。

这是我想出的代码。

@Autowired
@Qualifier("restTemplate")
RestTemplate restTemplate;

public String post(String lambdaApiBasicUri, String pathPostfix, String reqBody) throws Exception {
    HttpEntity<String> requestEntity = new HttpEntity<String>(reqBody, createHeaders());  
    ResponseEntity<String> responseEntity = restTemplate.exchange(  
            createReqUrl(lambdaApiBasicUri, pathPostfix), 
            HttpMethod.POST, 
            requestEntity, 
            String.class);

    return responseEntity.getBody();
}

这适用于所有情况,除非来自API的一条特定错误消息的主体中包含<>符号。在这种情况下,它会给我以下错误:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://example.com/abc": Attempted read from closed stream.; nested exception is java.io.IOException: Attempted read from closed stream.
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:673)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:620)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:538)

我从谷歌搜索中了解到,当我们尝试多次“消耗”响应时,会抛出此异常。但是问题是,我什至没有接触过responseEntity.getBody();被调用的那部分。该错误由restTemplate.exchange()调用本身引发。

我能够通过拼凑一个resttempalte.execute()而不是restTemplate.exchange()的电话来解决问题。但是我想知道为什么会引发此错误。

0 个答案:

没有答案
相关问题