使用Apache Camel发送POST请求

时间:2017-03-02 20:20:56

标签: rest post apache-camel camel-http

我能够使用Apache Camel向REST服务发送GET请求,现在我尝试使用Apache Camel向JSON主体发送POST请求。我无法弄清楚如何添加JSON主体并发送请求。如何添加JSON正文,发送请求并获取响应代码?

4 个答案:

答案 0 :(得分:4)

下面你可以找到一个发送(每2秒)json的示例Route, 使用POST方法到服务器,在示例中它是localhost:8080 / greeting。还有一种方法可以获得响应:

from("timer://test?period=2000")
    .process(exchange -> exchange.getIn().setBody("{\"title\": \"The title\", \"content\": \"The content\"}"))
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/greeting")
    .process(exchange -> log.info("The response code is: {}", exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE)));

通常手动准备json不是一个好主意。你可以使用例如

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-gson</artifactId>
</dependency>

为您执行编组。假设您定义了Greeting类,您可以通过删除第一个处理器并使用以下代码来修改Route:

.process(exchange -> exchange.getIn().setBody(new Greeting("The title2", "The content2")))
.marshal().json(JsonLibrary.Gson)

进一步阅读:http://camel.apache.org/http.html 值得注意的是,还有http4组件(他们使用不同版本的Apache HttpClient)。

答案 1 :(得分:2)

//This code is for sending post request and getting response
public static void main(String[] args) throws Exception {
    CamelContext c=new DefaultCamelContext();       
    c.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {          
            from("direct:start")
            .process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                System.out.println("i am worlds fastest flagship processor ");
                exchange.getIn().setHeader("CamelHttpMethod", "POST");
                exchange.getIn().setHeader("Content-Type", "application/json");
                exchange.getIn().setHeader("accept", "application/json");
                }
                })
              // to the http uri
                .to("https://www.google.com")
       // to the consumer
                .to("seda:end");
        }
    });



    c.start();
    ProducerTemplate pt = c.createProducerTemplate();
      // for sending request 
    pt.sendBody("direct:start","{\"userID\": \"678\",\"password\": \"password\", 
  \"ID\": \"123\"  }");
    ConsumerTemplate ct = c.createConsumerTemplate();
    String m = ct.receiveBody("seda:end",String.class);
    System.out.println(m);
}

答案 2 :(得分:1)

这是你可以做到的:

from("direct:start")
 .setHeader(Exchange.HTTP_METHOD, constant("POST"))
 .to("http://www.google.com");

当前Camel Exchange的正文将获得POSTED到URL终点。

答案 3 :(得分:0)

请注意,尽管您可能希望显式设置HTTP方法,但不必这样做。以下来自Camel's http component documentation

将使用哪种HTTP方法

以下算法用于确定应使用哪种HTTP方法:

  1. 使用作为端点配置(httpMethod)提供的方法。
  2. 使用标头(Exchange.HTTP_METHOD)中提供的方法。
  3. 获取标题中是否提供查询字符串。
  4. 如果端点配置有查询字符串,则获取。
  5. 如果有要发送的数据(正文不为null),则进行POST。
  6. 否则获取。

换句话说,如果您有正文/数据且条件1-4不适用,则默认情况下它将过帐。这正在我实施的路线上进行。