How to send a request with POST parameters in Nett

2019-07-02 01:47发布

问题:

I'm trying to send a request with POST parameters in Netty.

I searched Netty API, Google, and here (Stack Overflow)

but didn't find any good way to do it. (It could be my fault of terrible searching skill :'( If so, I apologize)

Is there any API to do it easily?

Or do I have to do it by encoding all parameters and setting it in the content by myself?

Please let me know any good way to do it.

回答1:

Here's an example of how you would do a file upload:

https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/http/upload

If you don't want to upload a file, just ignore the MIME multipart bit.

Try something like:

HttpRequest httpReq=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,uri);
httpReq.setHeader(HttpHeaders.Names.HOST,host);
httpReq.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.KEEP_ALIVE);
httpReq.setHeader(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
httpReq.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");     
String params="a=b&c=d";
ChannelBuffer cb=ChannelBuffers.copiedBuffer(params,Charset.defaultCharset());
httpReq.setHeader(HttpHeaders.Names.CONTENT_LENGTH,cb.readableBytes());
httpReq.setContent(cb);

See Sending POST params with Netty and why isn't DefaultHttpDataFactory not in the releases?



标签: netty