[英]Consume JSON from another API using Apache Camel and write it in CSV
[英]How call an api with the parameters obtained from another api in apache camel?
我通过 apache 调用了 REST api 并对其进行了反序列化。 我需要调用另一个 API,其编号是我从调用前一个 api 时收到的参数。 我是通过以下方式做到的 -
public Collection<String> nos;
from("direct:further").tracing()
.log("body: " + body().toString())
.setBody().constant(null)
.setHeader("CamelHttpMethod")
.simple("GET")
.setHeader("Authorization")
.simple("Bearer "+"${header.jwt}")
.to("https://call/api/that/returns/numbers")
.choice()
.when().simple("${header.CamelHttpResponseCode} == 200").unmarshal().json(JsonLibrary.Jackson, Abc.class)
.process(
ex->{
Quantity quantity = ex.getIn().getBody(Abc.class);
List<Variations> variationsList = Arrays.stream(quantity.getResources().getVariations()).toList();
nos=variationsList.stream().map(Variations::getNo).collect(
Collectors.toList());
nos.forEach(s -> { //Since nos is a collection of String I would like to iterate through it
String url="https://call/another/api/with/number"+"?"+s;//the link with the number as the parameter
from("direct:start") //This is not working. I not able to call the url
.setHeader("CamelHttpHeader")
.simple("GET")
.setHeader("Authorization")
.simple("Bearer "+"${header.jwt}")
.log("I did call the numbers") //This is also not getting printed
.to(url);
});
}).log("I am out of the loop" + body())
.otherwise()
.log("Error!!!");
我无法使用我收到的号码呼叫另一个 api,而我收到的号码是呼叫第一个 api。 我该怎么做? 我也试着这样称呼它
from("rest:get:"+url).tracing()
.setHeader("CamelHttpHeader")
.simple("GET")
.setHeader("Authorization")
.simple("Bearer "+"${header.jwt}")
.log("I did call the numbers").to(url);
但不幸的是,上面的代码在循环内也不起作用。 我在方法定义之外声明了集合号。 我应该如何从 nos 集合中存储的号码中调用另一个 API ? 我应该在 lambda function 外面还是里面打电话给另一个 Api ?
与其尝试在处理器内定义新路由,不如将数字集合存储到正文并使用 split 调用动态生产者端点toD
,它可以使用简单的语言来构造带有来自正文、标题、属性等的值的 uri。
如果您以后需要收集所有回复到说列表,您可以创建自定义AggregationStrategy或使用灵活的。
Camel 3.18.2 使用单元测试的简单示例
package com.example;
import java.util.ArrayList;
import org.apache.camel.AggregationStrategy;
import org.apache.camel.Exchange;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.AggregationStrategies;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
public class NumbersAPITests extends CamelTestSupport {
@Test
public void testAPILogic() throws Exception {
replaceHttpEndpointWithSimpleResponse("requestNumbersFromAPI",
"[1,2,3,4,5]");
replaceHttpEndpointWithSimpleResponse("requestDataWithIdFromAPI",
"{ \"id\"=\"${body}\", \"data\":\"some data\" }");
weaveAddMockendpointAsLast("requestNumbersFromAPI", "result");
weaveAddMockendpointAsLast("requestDataWithIdFromAPI", "splitResult");
MockEndpoint mockResultEndpoint = getMockEndpoint("mock:result");
mockResultEndpoint.expectedMessageCount(1);
MockEndpoint mockSplitResultEndpoint = getMockEndpoint("mock:splitResult");
mockSplitResultEndpoint.expectedMessageCount(5);
startCamelContext();
template.sendBodyAndHeader("direct:requestNumbersFromAPI", null, "jwt", "not-valid-jwt");
mockResultEndpoint.assertIsSatisfied();
mockSplitResultEndpoint.assertIsSatisfied();
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder(){
@Override
public void configure() throws Exception {
AggregationStrategy aggregationStrategy = AggregationStrategies
.flexible()
.accumulateInCollection(ArrayList.class);
from("direct:requestNumbersFromAPI")
.routeId("requestNumbersFromAPI")
.setBody().constant(null)
.setHeader("Authorization")
.simple("Bearer "+"${header.jwt}")
.to("https://call/api/that/returns/numbers")
.unmarshal().json(JsonLibrary.Jackson, Integer[].class)
.split(body(), aggregationStrategy)
.to("direct:requestDataWithIdFromAPI")
.end()
//Logs resulting exchange body, headers and properties.
.to("log:loggerName?showAll=true")
;
from("direct:requestDataWithIdFromAPI")
.routeId("requestDataWithIdFromAPI")
.setHeader("Authorization").simple("Bearer "+"${header.jwt}")
.log("Calling API with number: ${body}")
.toD("https://call/another/api/with/number/${body}")
;
}
};
}
@Override
public boolean isUseAdviceWith() {
return true;
}
private void replaceHttpEndpointWithSimpleResponse(String routeId, String simpleResponse) throws Exception {
AdviceWith.adviceWith(context(), routeId, a -> {
a.weaveByToUri("http*")
.replace()
.setHeader(Exchange.HTTP_RESPONSE_CODE).constant(200)
.setBody().simple(simpleResponse);
});
}
private void weaveAddMockendpointAsLast(String routeId, String mockName) throws Exception {
AdviceWith.adviceWith(context(), routeId, a -> {
a.weaveAddLast()
.to("mock:" + mockName);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.