Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode http POST data in Java?

I'm using Netty, and I've got to accept and parse http POST requests. As far as I can tell, Netty doesn't have built-in support for POSTs, only GETs. (It's a fairly low-level library that deals with primitive network operations. Using a servlet container, which does all this stuff out of the box, is not an option.)

If I have the content of a POST request as an array of bytes, what's the fastest and most bug-free way to parse it into a Map of parameters?

I could write this myself, but there must be some methods built into the JDK that make this easier. And I'll bet there are some gotchas and corner cases to deal with.

like image 466
ccleve Avatar asked Dec 28 '11 18:12

ccleve


1 Answers

Netty has an advanced POST request decoder (HttpPostRequestDecoder) which can decode Http Attributes, FileUpload Content with chunked encoding.

Here is an simple form decoding example

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
  HttpRequest request = (HttpRequest) e.getMessage();
  HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), request);

  InterfaceHttpData data = decoder.getBodyHttpData("fromField1");
  if (data.getHttpDataType() == HttpDataType.Attribute) {
     Attribute attribute = (Attribute) data;
     String value = attribute.getValue()
     System.out.println("fromField1 :" + value);
  }
}
like image 125
Jestan Nirojan Avatar answered Sep 24 '22 05:09

Jestan Nirojan