在Java Vert.x上处理post请求的有效方法?
这就是我目前在vert.x服务器上处理post请求的方式:在Java Vert.x上处理post请求的有效方法?,java,post,vert.x,Java,Post,Vert.x,这就是我目前在vert.x服务器上处理post请求的方式: router.post("/test").handler(context -> context.request().bodyHandler(body -> { try { JsonObject jsonObject = new JsonObject(body.toString()); ... } catch(Exception e) { } })); 我使用Postman发
router.post("/test").handler(context -> context.request().bodyHandler(body -> {
try {
JsonObject jsonObject = new JsonObject(body.toString());
...
} catch(Exception e) { }
}));
我使用Postman发送测试请求,其中body的数据为“raw-application/json”
这很有效。但是,这是正确的方法吗
我还尝试将数据作为“表单数据”中的参数发送,但无法获取参数。下面打印出整个请求,我可以看到数据,但无法将其解析为json或映射
router.post("/test").handler(context ->
context.request().bodyHandler(System.out::println));
感谢您的帮助。谢谢。有很多方法可以为请求处理程序编程。 您可以在本文档中找到不同的方法 以下是我在编写处理程序时更喜欢的方法
package org.api.services.test;
import org.api.services.test.CustomDTO;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
public class TestApi extends AbstractVerticle {
@Override
public void start(Future<Void> startFuture) throws Exception {
super.start(startFuture);
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
//register a router for post request that accepts only requests with */json MIME type on exact path /test.
router.post("/test/").consumes("*/json").handler(this::testHandler);
...
}
private void testHandler(RoutingContext routingContext) {
//recommended way to extract json
JsonObject jsonObject = routingContext.getBodyAsJson();
//automatically map json to custom object
CustomDTO customDTO = Json.decodeValue(routingContext.getBodyAsString(), CustomDTO.class);
...
}
}
package org.api.services.test;
导入org.api.services.test.CustomDTO;
导入io.vertx.core.AbstractVerticle;
导入io.vertx.core.Future;
导入io.vertx.core.json.json;
导入io.vertx.core.json.JsonObject;
导入io.vertx.ext.web.Router;
导入io.vertx.ext.web.RoutingContext;
导入io.vertx.ext.web.handler.BodyHandler;
公共类TestApi扩展了AbstractVerticle{
@凌驾
public void start(Future startFuture)引发异常{
超级启动(开始未来);
路由器=路由器。路由器(vertx);
router.route().handler(BodyHandler.create());
//为post请求注册路由器,该路由器只接受精确路径/测试上具有*/json MIME类型的请求。
router.post(“/test/”).consumes(“*/json”).handler(this::testHandler);
...
}
私有void测试处理程序(RoutingContext RoutingContext){
//提取json的推荐方法
JsonObject JsonObject=routingContext.getBodyAsJson();
//自动将json映射到自定义对象
CustomDTO CustomDTO=Json.decodeValue(routingContext.getBodyAsString(),CustomDTO.class);
...
}
}
如果发送包含表单数据的请求,可以通过两种方式提取:
router.route().handler(BodyHandler.create())代码>之后,所有表单属性都将合并为请求参数
routingContext.request().getParam(“属性名称”)
routingContext.request().setExpectMultipart(true)代码>然后访问如下表单属性routingContext.request().formAttributes()
final Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
....
context.request().getParam("id")