2014-03-13 24 views

回答

5

以下代碼片段爲Netty 4.0.20 Final工作。它基於HttpSnoopClient示例http://netty.io/4.0/xref/io/netty/example/http/snoop/HttpSnoopClient.html

// Prepare the HTTP request. 
String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); 
FullHttpRequest request = new DefaultFullHttpRequest(
      HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getRawPath()); 

request.headers().set(HttpHeaders.Names.HOST, host); 
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); // or HttpHeaders.Values.CLOSE 
request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); 
request.headers().add(HttpHeaders.Names.CONTENT_TYPE, "application/json"); 
ByteBuf bbuf = Unpooled.copiedBuffer("{\"jsonrpc\":\"2.0\",\"method\":\"calc.add\",\"params\":[1,2],\"id\":1}", StandardCharsets.UTF_8); 
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bbuf.readableBytes()); 
request.content().clear().writeBytes(bbuf); 

// Send the HTTP request. 
channel.writeAndFlush(request); 
+1

這在過去的幾個小時裏一直困擾着我。祕訣在於使用「FullHttpRequest」接口而不是「HttpRequest」! –

相關問題