简体   繁体   English

使用 Apache Camel 发送 POST 请求

[英]Send POST Request using Apache Camel

I was able to send a GET request using Apache Camel to a REST service and now I'm trying to send a POST request with a JSON body using Apache Camel.我能够使用 Apache Camel 向 REST 服务发送 GET 请求,现在我正在尝试使用 Apache Camel 发送带有 JSON 正文的 POST 请求。 I wasn't able to figure out how to add the JSON body and send the request.我无法弄清楚如何添加 JSON 正文并发送请求。 How can I add a JSON body, send the request and get the response code?如何添加 JSON 正文、发送请求并获取响应代码?

Below you can find a sample Route which sends (every 2 seconds) the json, using POST method to the server, in the example it is localhost:8080/greeting.您可以在下面找到一个示例路由,它使用 POST 方法向服务器发送(每 2 秒)json,在示例中它是 localhost:8080/greeting。 There is also a way to get the response presented:还有一种方法可以获得响应:

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)));

Usually it is not a good idea to prepare json manually.通常手动准备json不是一个好主意。 You can use eg你可以使用例如

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

to perform marshalling for you.为您执行编组。 Assuming you have a Greeting class defined you can modify the Route by removing the first processor and using the following code instead:假设您定义了 Greeting 类,您可以通过删除第一个处理器并使用以下代码来修改路由:

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

Further reading: http://camel.apache.org/http.html It is worth noting that there is also http4 component (they use different version of Apache HttpClient under the hood).进一步阅读: http ://camel.apache.org/http.html 值得注意的是还有 http4 组件(它们在引擎盖下使用不同版本的 Apache HttpClient)。

This is how you can do it:你可以这样做:

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

Current Camel Exchange's body will get POSTED to the URL end point.当前 Camel Exchange 的主体将被发布到 URL 端点。

//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);
}

Note that while you may prefer to explicitly set the HTTP method, you don't have to.请注意,虽然您可能更喜欢显式设置 HTTP 方法,但您不必这样做。 The following is from Camel's http component documentation :以下来自Camel 的 http 组件文档

WHICH HTTP METHOD WILL BE USED将使用哪种 HTTP 方法

The following algorithm is used to determine what HTTP method should be used:以下算法用于确定应使用哪种 HTTP 方法:

  1. Use method provided as endpoint configuration (httpMethod).使用作为端点配置提供的方法 (httpMethod)。
  2. Use method provided in header (Exchange.HTTP_METHOD).使用标头中提供的方法 (Exchange.HTTP_METHOD)。
  3. GET if query string is provided in header.如果在标头中提供查询字符串,则为 GET。
  4. GET if endpoint is configured with a query string.如果端点配置了查询字符串,则为 GET。
  5. POST if there is data to send (body is not null). POST 如果有数据要发送(正文不为空)。
  6. GET otherwise.否则得到。

In other words, if you have a body/data and conditions 1-4 don't apply, it will POST by default.换句话说,如果您有正文/数据并且条件 1-4 不适用,则默认情况下它将 POST。 This is working on routes I've implemented.这是我已经实施的路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM