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

Vert.x - Get parameters from POST request

我正在尝试创建一个 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);
    }

}

}

你知道我怎样才能从 POST 得到 "bla" 吗?

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

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"}'

... 将 return:

$ 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
  • 处定义一个端点
  • 处理发布到该端点的内容