Reputation: 39
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:
@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);
}
}
}
Do you know how can I get the "bla" from POST?
Upvotes: 2
Views: 5656
Reputation: 47895
Try the following router and handler:
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);
}
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:
http://localhost:9000/analyze
Upvotes: 4