使用camel producertemplate和http时没有得到http响应体

时间:2012-09-06 18:28:39

标签: java spring apache-camel

我正在尝试使用http://camel.apache.org/http.html上指定的producertemplate来调用我的简单GET休息服务调用。我在这里以google.com为例。这是来自未在任何容器上运行的独立客户端。我在这里做的不是什么?

SpringCamelContext camelcontext = (SpringCamelContext) springContext.getBean("camelcontextbean");

ProducerTemplate template = camelcontext.createProducerTemplate();
camelcontext.start();
Exchange exchange = template.send("http://www.google.com/search", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_QUERY, "hl=en&q=activemq");
            }
   });

   Message out = exchange.getOut();
System.out.println("Response from http template is "+exchange.getOut().getBody());
   System.out.println("status header is "+out.getHeader(Exchange.HTTP_RESPONSE_CODE));

我没有得到任何回应。输出是:

来自http模板的响应为空

状态标头为空

4 个答案:

答案 0 :(得分:4)

它与你从Spring创建camelContext的方式有关,因为如果我删除它并从 DefaultCamelContext 中获取 CamelContext 我没有看到问题:

import org.apache.camel.*;
import org.apache.camel.impl.DefaultCamelContext;

public class Main {

    public static void main(String ... args){
        CamelContext camelContext = new DefaultCamelContext();
        ProducerTemplate template = camelContext.createProducerTemplate();

        Exchange exchange = template.send("http://www.google.com/search", new Processor() {
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_QUERY, "hl=en&q=activemq");
            }
        });

        Message out = exchange.getOut();
        System.out.println("Response from http template is "+exchange.getOut().getBody());
        System.out.println("status header is "+out.getHeader(Exchange.HTTP_RESPONSE_CODE));
    }

}

产量

Response from http template is org.apache.camel.converter.stream.CachedOutputStream$WrappedInputStream@26659db7
status header is 200

答案 1 :(得分:2)

send方法只是一种模式,您可以使用请求方法获得更多运气(请参阅官方documentation

Exchange exchange = template.request("http://www.google.com/search", new Processor() {
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeader(Exchange.HTTP_QUERY, "hl=en&q=activemq");
        }
});

答案 2 :(得分:1)

您可以通过exchange.getIn().getBody(String.class)

访问您的回复

答案 3 :(得分:0)

Exchange exchange = template.request("http://www.google.com/search", new Processor() {
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeader(Exchange.HTTP_QUERY, "hl=en&q=activemq");
        }
});

如果我有正文和标题,如何拨打邮政服务。