can I modify the content-type of http request ?

36 views
Skip to first unread message

Zhiyuan Lei

unread,
Sep 28, 2022, 9:19:47 AM9/28/22
to vert.x
I wrote a server with  vertx 4.3.1 .
users can post form data to my server, so I will process like this 

```
Route opRouter = router.post(path);
opRouter.handler(BodyHandler.create());
opRouter.handler(ctx -> {});
```
but BodyHandler need the content is multipart/form-data  or application/x-www-form-urlencoded

because of the historical reasons, some clients will not set the content-type,or use wrong content-type, but the body is right

so I want to do somethings like this

```
opRouter.handler(// set the content type of request )
opRouter.handler(BodyHandler.create());
opRouter.handler(ctx -> {
```

is it possible? or how to do it? thanks for any help


Paulo Lopes

unread,
Oct 3, 2022, 6:24:56 AM10/3/22
to vert.x
Hi, yes you can do it. All you need to do is modify the request "before" the body handler is triggered. For example I've created the following unit test:

  @Test
  public void testFormURLEncodedPatchingHeader() throws Exception {
    router.clear();

    router.route()
      .handler(ctx -> {
        ctx
          .request()
          .headers().set("content-type", "application/x-www-form-urlencoded");
          ctx.next();
      });

    router.route().handler(BodyHandler.create());

    router.route()
      .handler(rc -> {
      MultiMap attrs = rc.request().formAttributes();
      assertNotNull(attrs);
      assertEquals(3, attrs.size());
      assertEquals("junit-testUserAlias", attrs.get("origin"));
      assertEquals("ad...@foo.bar", attrs.get("login"));
      assertEquals("admin", attrs.get("pass word"));
      rc.response().end();
    });
    testRequest(HttpMethod.POST, "/", req -> {
      Buffer buffer = Buffer.buffer();
      buffer.appendString("origin=junit-testUserAlias&login=admin%40foo.bar&pass+word=admin");
      req.headers().set("content-length", String.valueOf(buffer.length()));
      req.write(buffer);
    }, 200, "OK", null);
  }


As you can see from the bottom I'm requesting a form encoded request without the content type header.

Then from the top, the request will be enhanced with a content type header, passed to the body handler, which will properly parse it (note, if you remove the previous step the test fails as body handler will not process) and finally assert that the data is present in the last server handler.

Cheers,
Paulo
Reply all
Reply to author
Forward
0 new messages