java 使用 Apache Camel 发送 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42565190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:43:57  来源:igfitidea点击:

Send POST Request using Apache Camel

javarestpostapache-camelcamel-http

提问by user6641655

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. I wasn't able to figure out how to add the JSON body and send the request. How can I add a JSON body, send the request and get the response code?

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

回答by kris_k

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. There is also a way to get the response presented:

您可以在下面找到一个示例路由,它使用 POST 方法向服务器发送(每 2 秒)json,在示例中它是 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)));

Usually it is not a good idea to prepare json manually. You can use e.g.

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

<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.htmlIt 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)。

回答by user12766534

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

回答by Saurabh Nayar

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 端点。