user2953423 user2953423 - 5 months ago 112
reST (reStructuredText) Question

Vert.x - Get parameters from POST request

Im trying to create a Vert.x Rest service that responds to POST requests on some URL\analysis.

Using the following command

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

I want to extract "bla" from the command and perform simple text analysis on it.:

Here is the draft of my code:

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

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

// Create Http server and pass the 'accept' method to the request handler
listen(config().getInteger("http.port", 9000),
result -> {
if (result.succeeded()) {
System.out.println("Http server completed..");
} else {;
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());
String postedText = body.getString("text");
response.putHeader("content-type", "text/html");
response.end("you posted json which contains the following " + postedText);



Do you know how can I get the "bla" from POST?

Answer Source

Try the following router and handler:

Router router = Router.router(vertx);
// add a handler which sets the request body on the RoutingContext.
// expose a POST method endpoint on the URI: /analyze"/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);

With the above code in place this CURL command ...

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

... will 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

Looking at your question you have defined an endpoint named /analyze but then you suggested this CURL command: curl -D- http://localhost:8080 -d '{"text":"bla"}' which doesn't talk to the /analyze endpoint. Perhaps that's part of the issue or maybe that's just a typo when preparing the question. Regardless, the code I have supplied above will:

  • Define an endpoint at http://localhost:9000/analyze
  • Handle content POSTed to that endpoint
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download