[英]Sending HTTP Post Request in Netty
I'm trying to wrap my mind around how I would go about constructing an HTTP Post request for a web server. 我正在设法将精力集中在如何为Web服务器构造HTTP Post请求上。
I found this code 我找到了这段代码
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);
From what I can deduce, it appears that this request will send a POST request with two values, a and c, which are equal to b and d, respectively. 据我所知,似乎该请求将发送一个带有两个值a和c的POST请求,这两个值分别等于b和d。
What I'd like to be able to do is submit a JSON request. 我想做的就是提交JSON请求。 For example, if my post-data needed to be
例如,如果我的发布数据需要
{
"test": "value",
"key": "value",
}
would I just replace the a=b&c=d with that string itself? 我会只用该字符串本身替换a = b&c = d吗? Also, I must have the content-type set to application/json.
另外,我必须将内容类型设置为application / json。
If anyone could help me or point me in the right direction, I would really appreciate it. 如果有人能帮助我或指出正确的方向,我将不胜感激。
My example for JSON requests via Netty 4.x to localhost/target
: 我的示例是通过Netty 4.x到
localhost/target
JSON请求:
String JSON_DATA = "{ \"test\": \"value\", \"key\": \"value\"}";
FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, "/target",
wrappedBuffer(JSON_DATA.getBytes(CharsetUtil.UTF_8)));
request.headers().add(HttpHeaderNames.HOST, "127.0.0.1");
request.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
outboundChannel.writeAndFlush(request);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.