Vert.x - 从POST请求中获取参数

时间:2017-09-23 13:33:02

标签: java rest post vert.x

我正在尝试创建一个Vert.x Rest服务,该服务响应某些URL \ analysis上的POST请求。

使用以下命令

  

curl -D- http://localhost:8080 \ analyze -d' {" text":" bla"}'

我想提取" bla"从命令中执行简单的文本分析。:

以下是我的代码草稿:

    @Override
public void start(Future<Void> fut) throws Exception {

    router = Router.router(vertx);
    router.post("/analyze").handler(this::analyze);

    // Create Http server and pass the 'accept' method to the request handler
    vertx.createHttpServer().requestHandler(router::accept).
            listen(config().getInteger("http.port", 9000),
                    result -> {
                        if (result.succeeded()) {
                            System.out.println("Http server completed..");
                            fut.complete();
                        } else {
                            fut.fail(result.cause());
                            System.out.println("Http server failed..");
                        }
                    }
            );
}


private void analyze(RoutingContext context) {
    HttpServerResponse response = context.response();
    String bodyAsString = context.getBodyAsString();
    JsonObject body = context.getBodyAsJson();

    if (body == null){
        response.end("The Json body is null. Please recheck.." + System.lineSeparator());
    }
    else
    {
        String postedText = body.getString("text");
        response.setStatusCode(200);
        response.putHeader("content-type", "text/html");
        response.end("you posted json which contains the following " + postedText);
    }

}

}

你知道我怎么能得到&#34; bla&#34;从POST?

1 个答案:

答案 0 :(得分:2)

尝试以下路由器和处理程序:

Router router = Router.router(vertx);
// add a handler which sets the request body on the RoutingContext.
router.route().handler(BodyHandler.create());
// expose a POST method endpoint on the URI: /analyze
router.post("/analyze").handler(this::analyze);

// handle anything POSTed to /analyze
public void analyze(RoutingContext context) {
    // the POSTed content is available in context.getBodyAsJson()
    JsonObject body = context.getBodyAsJson();

    // a JsonObject wraps a map and it exposes type-aware getters
    String postedText = body.getString("text");

    context.response().end("You POSTed JSON which contains a text attribute with the value: " + postedText);
}

使用上面的代码,这个CURL命令......

curl -D- http://localhost:9000/analyze -d '{"text":"bla"}'

...将返回:

$ curl -D- http://localhost:9000/analyze -d '{"text":"bla"}'
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 67
Set-Cookie: vertx-web.session=21ff020c9afa5ec9fd5948acf64c5a85; Path=/

You POSTed JSON which contains a text attribute with the value: bla

查看您的问题,您已定义了一个名为/analyze的端点,但随后您建议使用此CURL命令:curl -D- http://localhost:8080 -d '{"text":"bla"}',它不与/analyze端点通信。也许这是问题的一部分,或者在准备问题时这可能只是一个错字。无论如何,我上面提供的代码将:

  • http://localhost:9000/analyze
  • 定义端点
  • 处理发布到该终端的内容