0

I need to create a server application with Netty that will receive requests both like "GETs" or "POSTs". In case of GET requests, the parameters would come as query parameters.

I have been checking that HttpRequestDecoder would be suitable for the GET requests, and HttpPostRequestDecoder for the post. But how could I handle both at the same time?

Not very familiar with Netty, so I would appretiate a little bit of help :)

Nino Walker
  • 2,742
  • 22
  • 30
Enrique Cordero
  • 33
  • 1
  • 1
  • 6

2 Answers2

2

The netty provisions us to handle a request as a pipeline where you define the pipeline as a sequence of handlers.

One sequence could be like this:

p.addLast ("codec", new HttpServerCodec ());
p.addLast ("handler", new YourHandler());

where p is an instance of ChannelPipeline interface. You can define the YourHandler class as follows:

public class YourHandler extends ChannelInboundHandlerAdapter
{
    @Override
    public void channelRead (ChannelHandlerContext channelHandlerCtxt, Object msg)
        throws Exception
    {
        // Handle requests as switch cases. GET, POST,...
        // This post helps you to understanding switch case usage on strings:
        // http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java
        if (msg instanceof FullHttpRequest)
        {
            FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
            switch (fullHttpRequest.getMethod ().toString ())
            {
                case "GET":
                case "POST":
                ...
            }
        }
    }
}
Corehacker
  • 267
  • 1
  • 2
  • 7
  • I have tried this approach, but I can not map the msg as FullHttpRequest. Channel read is called many times with different objects: DefaultHttpRequest, LastHttpContent. – Enrique Cordero Oct 18 '13 at 12:59
  • You can use the instance of directive to know which kind of object it is: if (msg instanceof FullHttpRequest) { FullHttpRequest fullHttpRequest = (FullHttpRequest) msg; } I have updated the code snippet in my answer for more clarity! – Corehacker Oct 18 '13 at 17:26
  • Adding an [HttpRequestAggregator](http://netty.io/4.1/api/io/netty/handler/codec/http/HttpObjectAggregator.html) to the pipeline will do the work of aggregating an `HttpMessage` and its `HttpContents` into a `FullHttpRequest`. – Matt May 31 '16 at 10:59
0

You want to first check the request type and switch on the value (GET/POST/PUT/DELETE etc...)

http://docs.jboss.org/netty/3.1/api/org/jboss/netty/handler/codec/http/HttpMethod.html

Latheesan
  • 23,247
  • 32
  • 107
  • 201