使用 ProducerTemplate 进行测试时,Camel 主体丢失并显示 500 状态
Camel body is lost with 500 status when testing with ProducerTemplate
我有一条简单的骆驼路线:
from("jetty:http://localhost:8080/path")
.setBody(simple("<zzz>zzz</zzz>"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("500"))
.setHeader(Exchange.CONTENT_TYPE, simple("application/xml"));
我有一个代码如下的测试用例:
Exchange ex = producerTemplate.request("http://localhost:8080/path", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
一旦将响应代码设置为 500,正文就会返回 null。事实上 ex.hasOut() 是假的。
当使用 curl 测试时,正文被返回。所以是producerTemplate的测试用例使用导致了问题。
我需要做什么才能得到我期望的尸体?
Http 组件将 5xx 状态代码转换为 HttpOperationFailedException
。
您可以使用选项 throwExceptionOnFailure=false
关闭此行为。
Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.
Exchange ex = template.request("http://localhost:8080/path?throwExceptionOnFailure=false", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getMessage().getBody());
或者从HttpOperationFailedException
对象获取响应体。
Exchange ex = template.request("http://localhost:8080/path", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getException(HttpOperationFailedException.class).getResponseBody());
我有一条简单的骆驼路线:
from("jetty:http://localhost:8080/path")
.setBody(simple("<zzz>zzz</zzz>"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, simple("500"))
.setHeader(Exchange.CONTENT_TYPE, simple("application/xml"));
我有一个代码如下的测试用例:
Exchange ex = producerTemplate.request("http://localhost:8080/path", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
一旦将响应代码设置为 500,正文就会返回 null。事实上 ex.hasOut() 是假的。
当使用 curl 测试时,正文被返回。所以是producerTemplate的测试用例使用导致了问题。
我需要做什么才能得到我期望的尸体?
Http 组件将 5xx 状态代码转换为 HttpOperationFailedException
。
您可以使用选项 throwExceptionOnFailure=false
关闭此行为。
Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.
Exchange ex = template.request("http://localhost:8080/path?throwExceptionOnFailure=false", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getMessage().getBody());
或者从HttpOperationFailedException
对象获取响应体。
Exchange ex = template.request("http://localhost:8080/path", (e) -> {
e.getIn().setBody(requestBody);
e.getIn().setHeader("Content-Type", "application/xml");
});
log.info(ex.getException(HttpOperationFailedException.class).getResponseBody());