简体   繁体   English

如何从RoutingContext获取邮件正文?

[英]How to get message body from RoutingContext?

I created a vert.x HTTP server and I want to receive messages from clients in json format. 我创建了一个vert.x HTTP服务器,我希望以json格式从客户端接收消息。 This is my code: 这是我的代码:

public class HttpServerVerticle extends AbstractVerticle {
    @Override
    public void start(Future<Void> future) {
        Router router = Router.router(vertx)
            .exceptionHandler(ex -> log.error("Error: " + ex));
        router.route().handler(BodyHandler.create());
        router.route("/getData").handler(this::getRequestHandler);

        HttpServerOptions serverOptions = new HttpServerOptions();
        vertx.createHttpServer(serverOptions)
                .requestHandler(router::accept)
                .listen(9539, result -> {
                    if (result.succeeded()) {
                        future.complete();
                    } else {
                        future.fail(result.cause());
                    }
                });
    }

    private void getRequestHandler(RoutingContext request) {
        JsonObject data = request.getBodyAsJson();  // In this place I had exception
        ...
        request.response().end("{\"reply\":\"ok\"}");
    }
}

When my handler was fire and I get some message from the client I get this exception: 当我的处理程序开火并且我从客户端收到一些消息时,我得到了这个异常:

io.vertx.core.json.DecodeException: Failed to decode:Unexpected end-of-input: expected close marker for Object (start marker at [Source: (String)"{"ClientRequest":["ok"],"Type":"Test"[truncated 678 chars]; line: 1, column: 1])

How can I avoid this exception and all time get the full message? 如何避免此异常并始终获取完整消息?

You should specify the HTTP method 您应该指定HTTP方法

router.route("/getData").handler(this::getRequestHandler);

is expecting an HTTP GET, but what you need is an HTTP POST: 期待HTTP GET,但您需要的是HTTP POST:

router.post("/getData")
  .consumes("application/json")
  .handler(this::getRequestHandler);

will accept json in the body. 将接受身体中的json。 The consumes is optional and enforces the client to only send json. 消耗是可选的,并强制客户端仅发送json。

I would also suggest to name the route "/data" instead of "/getData" to conform with the concept of RESTful APIs. 我还建议将路径命名为“/ data”而不是“/ getData”,以符合RESTful API的概念。

Its possible the client is not sending a valid json. 可能客户端没有发送有效的json。 This is a valid exception to handle in that case. 在这种情况下,这是一个有效的例外处理。 For logging the request, you can simply use request.getBodyAsString() before doing getBodyAsJson() 要记录请求,您可以在执行getBodyAsJson()之前使用request.getBodyAsString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM