从Camel Message Body获取HttpServletRequest和HttpServletResponse

时间:2016-06-01 00:47:01

标签: java apache-camel jetty

我正在尝试使用Camel Jetty或Camel HTTP组件向HTTP端点发送请求。我想知道是否可以将请求和响应转换为HttpServletRequest和HttpServletResponse对象。

我有以下路线:

from("direct://processing/callEndpoint")
    .to("jetty:http://www.google.com")
    .to("bean:processHttpResponse")

我正在使用Guice进行依赖注入,“bean:processHttpResponse”如下:

public class HttpResponseBean {

    public void processResponse(Exchange exchange) {

        HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
        HttpServletResponse response = exchange.getOut().getBody(HttpServletResponse.class);

    }
}

请求响应对象均为空。在调试/检查Exchange时,In Message是一个字节数组(byte []),Out Message为null。不确定如何继续..

2 个答案:

答案 0 :(得分:1)

请参阅消费者示例中的Camel Jetty

尝试像这样调用你的bean。

from("jetty:http://localhost:{{port}}/myapp/myservice").bean(HttpResponseBean,"processResponse");

public class HttpResponseBean {

    public void processResponse(Exchange exchange) {

         // we have access to the HttpServletRequest here and we can grab it if we need it
            HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class);

    }
}

答案 1 :(得分:1)

你应该实现像这样的处理器:

public class MyBean implements Processor {
    public void process(Exchange exchange) throws Exception {
        HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
        HttpServletResponse response = exchange.getOut().getBody(HttpServletResponse.class);
    }
}

如果你有像这样的@Configuration Spring上下文

@Configuration
class ApplicationConfiguration {

  @Bean
  public MyBean myBean() {
    return new MyBean();
  }

}

您应该可以在process语句中引用它,例如.process("bean:myBean")

如果您使用RouteBuilder构建路线,请使用SpringCamelContext以让Camel访问Bean。