Skip to content
Advertisement

Method to get and post Json object in Vertx

I’m new to Java and to backend development, and I really could use some help.

I am currently using Vert.x to develop a server that takes in a Json request that tells this server which file to analyze, and the server analyzes the file and gives a response in a Json format.

I have created an ImageRecognition class where there is a method called “getNum” which gets a json as an input and outputs a json containing the result.

But I am currently having trouble getting the Json file from the request.

public void start(Promise<Void> startPromise) throws Exception {
JsonObject reqJo = new JsonObject();

Router router = Router.router(vertx);
router.get("/getCall").handler(req ->{
  JsonObject subJson = req.getBodyAsJson();
  reqJo.put("name", subJson.getValue("name"));
  req.end(reqJo.encodePrettily());
});
router.post("/getCall").produces("*/json").handler(plateReq ->{
  plateReq.response().putHeader("content-tpye", "application/json");
  JsonObject num = imageRecogService.getNum(reqJo);
  plateReq.end(num.encodePrettily());
});
vertx.createHttpServer().requestHandler(router).listen(8080)
  .onSuccess(ok -> {
    log.info("http server running on port 8080");
    startPromise.complete();
  })
  .onFailure(startPromise::fail);

} }

Any feedback or solution to the code would be deeply appreciated!! Thank you in advance!!

Advertisement

Answer

You have several errors in your code:

1:

JsonObject reqJo = new JsonObject();

Router router = Router.router(vertx);
router.get("/getCall").handler(req ->{
  reqJo.put("name", subJson.getValue("name"));
});

You are modifying the reqJo object in handlers. I am not sure if this is thread safe, but a more common practice is to allocate the JsonObject object inside of request handlers and pass them to consequent handlers using RoutingContext.data().

2: Your two handlers are not on the same method (the first one is GET, while the second is POST). I assume you want them both be POST.

3: In order to extract multipart body data, you need to use POST, not GET.

4: You need to append a BodyHandler before any of your handlers that reads the request body. For example:

// Important!
router.post("/getCall").handler(BodyHandler.create());
// I changed to posts
router.post("/getCall").handler(req ->{
  JsonObject subJson = req.getBodyAsJson();
  reqJo.put("name", subJson.getValue("name"));
  req.end(reqJo.encodePrettily());
});

Otherwise, getBodyAsJson() will return null.

According to the Document of RoutingContext#getBodyAsJson, “the context must have first been routed to a BodyHandler for this to be populated.”

Read more: BodyHandler.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement