我创建了一个 vert.x HTTP 服务器,我想从客户端接收 json 格式的消息。 这是我的代码:
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\"}");
}
}
当我的处理程序发生火灾并且我从客户端收到一些消息时,我收到此异常:
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])
如何避免此异常并始终获取完整消息?
最佳答案
您应该指定 HTTP 方法
router.route("/getData").handler(this::getRequestHandler);
期待 HTTP GET,但您需要的是 HTTP POST:
router.post("/getData")
.consumes("application/json")
.handler(this::getRequestHandler);
将接受正文中的 json。 Consumer 是可选的,强制客户端仅发送 json。
我还建议将路由命名为“/data”而不是“/getData”,以符合 RESTful API 的概念。
关于java - 如何从RoutingContext中获取消息体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390175/