[英]How to write web-service response to file using camel?
我正在尝试从http://localhost:8089/mock/success
托管的REST Web服务获取响应,并使用Camel
将响应写入文件。 这是我在Java中为相同代码编写的路线-
from("direct:start")
.to("http://localhost:8089/mock/success")
.to("file://D:/tmp/restoutput");
这是我调用此路线的方式-
CamelContext ctx = new DefaultCamelContext();
RouteBuilder routebuilder = new RestToFileRoute();
System.out.println("invokeRestToFileRoute() started.");
try {
ctx.addRoutes(routebuilder);
ctx.start();
Thread.sleep(1000);
ctx.stop();
} catch (Exception e) {
e.printStackTrace();
}
我没有任何例外,但没有任何内容添加到文件中。 我是骆驼的新手,所以我无法猜测问题所在。 谁能帮我这个?
使用基于建议的计时器,写入文件时出现空指针异常。 这是修改后的代码-
from("timer://simpleTimer?repeatCount=1")
.to("http://localhost:8089/mock/success")
.process(exchange -> {System.out.println("Message: " + exchange.getOut().getBody(String.class));}) // Output: "Message: null"
.to("file://D:/tmp/restoutput");
根据文档,http组件的响应存储在交换机的外部。 文件为空的原因是因为它正在写入部分。
您可以尝试执行以下操作将外部主体复制到内部主体:
.setBody(simple("${out.body}"))
.to("file://D:/tmp/restoutput");
我不习惯用Java DSL编写路由,但是如果我没记错的话,它应该看起来像这样。
因此,终于在所有答案的帮助下使其起作用。 下面显示的是最终的工作代码。
使用路线-
from("timer://simpleTimer?repeatCount=1") .to("http://localhost:8089/mock/success") .process(exchange -> { String response = exchange.getIn().getBody(String.class); exchange.getOut().setBody(msg); }) .to("file://D:/tmp/?fileName=restoutput"); // This was missing earlier
使用ProducerTemplate-
ProducerTemplate template = new DefaultCamelContext().createProducerTemplate(); Exchange exchange = template.request("http://localhost:8089/mock/success", exchangeObjcet -> {}); String response = exchange.getOut().getBody(String.class)
第二个虽然没有将其写入文件。 使用Java的标准文件api可以轻松完成此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.