簡體   English   中英

在Java Vert.x上處理發布請求的有效方法?

[英]Efficient way to handle post requests on Java Vert.x?

這就是我目前在vert.x服務器上處理發布請求的方式:

router.post("/test").handler(context -> context.request().bodyHandler(body -> {
    try {
        JsonObject jsonObject = new JsonObject(body.toString());
        ... 
    } catch(Exception e) { }
}));

我正在使用Postman發送測試請求,其中正文的數據為“raw - application / json”。

這有效。 但是,這是正確的方法嗎?

我也嘗試將數據作為參數發送到“form-data”,但我無法獲取參數。 以下打印出整個請求,我可以看到數據,但無法將其解析為json或map。

router.post("/test").handler(context -> 
    context.request().bodyHandler(System.out::println));

任何幫助表示贊賞。 謝謝。

您可以通過多種方式為請求處理程序編程。 您可以在本文檔中找到不同的方法https://vertx.io/docs/vertx-web/java/

在編寫處理程序時,我更喜歡這種方法。

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);
        ...
    }
}

如果您要發送包含表單數據的請求,您可以提取兩種方式:

  1. 如果添加router.route().handler(BodyHandler.create()); 將所有表單屬性合並為請求參數。

默認情況下,正文處理程序會將任何表單屬性合並到請求參數中。 如果您不想要此行為,可以使用setMergeFormAttributes禁用它。

您可以使用routingContext.request().getParam("attribute_name")來提取它們

  1. 如果你沒有使用任何BodyHandler,你需要設置routingContext.request().setExpectMultipart(true); 然后訪問像這個routingContext.request().formAttributes()的form屬性routingContext.request().formAttributes()

如果您需要“表單數據”,則應在句柄前添加“BodyHandler”。

final Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
....
context.request().getParam("id")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM