Sending POST parameters with Netty and why isn't DefaultHttpDataFactory not in releases?

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);
String params="a=b&c=d";
ChannelBuffer cb=ChannelBuffers.copiedBuffer(params,Charset.defaultCharset());
httpReq.setHeader(HttpHeaders.Names.CONTENT_LENGTH,cb.readableBytes());
httpReq.setContent(cb);

      

Does not return a valid request. What is the correct way to send the post request, preferably by creating the parameter data manually rather than using the DataFactory. Also, why is HttpDataFactory not included in any of the editions?

+2


source to share


2 answers


You have written everything correctly, just add httpReq.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");

and your example will work. For more complex code, you need to add url encoding.



+2


source


DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString());
request.headers().set(HttpHeaders.Names.HOST, ip);
request.headers().set(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
HttpEntity httpEntity = new UrlEncodedFormEntity(nvps);
ByteBuf byteBuf = 
Unpooled.copiedBuffer(EntityUtils.toByteArray(httpEntity));
request.content().writeBytes(byteBuf);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,request.content().readableBytes());
fu.channel().writeAndFlush(request)

      



0


source







All Articles