简体   繁体   中英

Netty: adding a form field with binary data to a HTTP POST request

In Netty there is a HttpPostRequestEncoder class which has an addBodyAttribute(String name, String value) method. I need to POST a value with binary data, but I can not find a method which takes byte[] value instead of String value . Is it easily achievable by any other means?

One may try to use the following (supposely wrong) combination if in standard POST (application/x-www-form-urlencoded): 1) Creating his/her own data = InterfaceHttpData (based for instance on MemoryAttribute ) and filling it with a ChannelBuffer / ByteBuffer (according to Netty version) build from the given byte[] ( setContent() )

2) Use addBodyHttpData(InterfaceHttpData data)

But the issue is, as far as I know, RFC does not allow "byte" for application/x-www-form-urlencoded ; therefore the value will have to be encoded using default charset, which is likely to not produce the correct answear.

Edit: To leverage this, one can create the encoder accordingly to use multipart:

new HttpPostRequestEncoder(factory, req, true);

It should work...

A) So possibly you will have to first encoded your "byte" in a "text" way (7 bit way as BASE64 encoding), then create your attribute using the default constructor addBodyAttribute(String name, String value) and then decoding on server side the value back to binary using BASE64 decoder.

=> But this needs the server to perform special decoding action (BASE64)

B) Another option would be to create a multipart POST request and then create a "fictive" file upload, using for instance MemoryFileUpload , using the setContent() from your own ChannelBuffer / ByteBuffer (according to Netty version) build from the given byte[] ; therefore the server side will have to handle the bynary content as usual (no decoding needed).

After some digging into Netty sources I've found somewhat looking as a solution:

byte[] buf = new byte[200];
...
DefaultFullHttpRequest req = new DefaultFullHttpRequest(httpVersion, HttpMethod.POST, uri);
DefaultHttpDataFactory factory = new DefaultHttpDataFactory();
HttpPostRequestEncoder enc = new HttpPostRequestEncoder(factory, req, false, CharsetUtil.UTF_8, HttpPostRequestEncoder.EncoderMode.RFC1738);
Attribute attr = factory.createAttribute(req, "someBinaryVar");
attr.setContent(io.netty.buffer.Unpooled.wrappedBuffer(buf));
enc.addBodyHttpData(attr);
...
enc.finalizeRequest();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM