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

十年热恋 提交于 2019-12-11 03:41:41

问题


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 yield a valid request. What is the correct way to send a post request, preferably by constructing the parameters data manually as opposed to with the DataFactory. Also, why is HttpDataFactory not included in any of the releases?


回答1:


You wrote everything correct, 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:


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)


来源:https://stackoverflow.com/questions/7324680/sending-post-params-with-netty-and-why-isnt-defaulthttpdatafactory-not-in-the-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!