下面列出了怎么用 io.netty.handler.codec.http.HttpClientCodec 的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast("inflater", new HttpContentDecompressor());
// to be used since huge file transfer
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new HttpUploadClientHandler());
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
p.addLast(new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpContents.
//p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpSnoopClientHandler());
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
// Enable HTTPS if necessary.
// if (sslCtx != null) {
// pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// }
pipeline.addLast(new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast(new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpContents.
//pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpObjectAggregator(65536 * 3));
// pipeline.addLast(new HttpClientHandler(null, mHttpClientListener));
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
// 启用 HTTPS .
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpClientCodec());
// 如果不想自动处理内容压缩请移除下面这一行.
p.addLast(new HttpContentDecompressor());
// 如果不想处理HttpContents就放开下面这行注释.
//p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpSnoopClientHandler());
}
@Override
public void configure(final ChannelPipeline pipeline) {
final String scheme = connection.getUri().getScheme();
if (!WEB_SOCKET.equalsIgnoreCase(scheme) && !WEB_SOCKET_SECURE.equalsIgnoreCase(scheme)) {
throw new IllegalStateException(String.format("Unsupported scheme (only %s: or %s: supported): %s",
WEB_SOCKET, WEB_SOCKET_SECURE, scheme));
}
if (!supportsSsl() && WEB_SOCKET_SECURE.equalsIgnoreCase(scheme)) {
throw new IllegalStateException(String.format("To use %s scheme ensure that enableSsl is set to true in "
+ "configuration",
WEB_SOCKET_SECURE));
}
final int maxContentLength = cluster.connectionPoolSettings().maxContentLength;
handler = createHandler();
pipeline.addLast(HTTP_CODEC, new HttpClientCodec());
pipeline.addLast(AGGREGATOR, new HttpObjectAggregator(maxContentLength));
pipeline.addLast(WEB_SOCKET_HANDLER, handler);
pipeline.addLast(GREMLIN_ENCODER, webSocketGremlinRequestEncoder);
pipeline.addLast(GRELIN_DECODER, webSocketGremlinResponseDecoder);
}
@Override
public void channelCreated(Channel ch) throws Exception {
logger.debug("channelCreated. Channel ID: {}", ch.id());
NioSocketChannel channel = (NioSocketChannel) ch;
channel.config().setKeepAlive(true);
channel.config().setTcpNoDelay(true);
ChannelPipeline pipeline = channel.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpContentDecompressor());
pipeline.addLast(new HttpObjectAggregator(1024 * 1024 * 64));
pipeline.addLast(new ChunkedWriteHandler());
// pipeline.addLast(new ReadTimeoutHandler(requestHolder.route.getTimeoutInMilliseconds(), TimeUnit.MILLISECONDS));
pipeline.addLast(new BackHandler());
}
private Bootstrap bootstrap(ClientHandler handler) {
Bootstrap b = new Bootstrap();
b.group(new NioEventLoopGroup(1))
.channel(NioSocketChannel.class)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10 * 1000)
.handler(
new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new ReadTimeoutHandler(10 * 60 * 1000));
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpObjectAggregator(6553600));
p.addLast(handler);
}
});
return b;
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast("inflater", new HttpContentDecompressor());
// to be used since huge file transfer
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new HttpUploadClientHandler());
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
p.addLast(new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpContents.
//p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpSnoopClientHandler());
}
@Override
public void channelCreated(Channel channel) {
NioSocketChannel nioSocketChannel = (NioSocketChannel) channel;
nioSocketChannel.config().setTcpNoDelay(true).setKeepAlive(true);
final ChannelPipeline p = nioSocketChannel.pipeline();
//HTTPS
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(channel.alloc()));
}
p.addLast(new HttpClientCodec(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE));
p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
}
@SuppressWarnings("FutureReturnValueIgnored")
private void releaseDownloadChannel(Channel ch) {
if (ch.isOpen()) {
// The channel might have been closed due to an error, in which case its pipeline
// has already been cleared. Closed channels can't be reused.
try {
ch.pipeline().remove(ReadTimeoutHandler.class);
ch.pipeline().remove(HttpClientCodec.class);
ch.pipeline().remove(HttpDownloadHandler.class);
} catch (NoSuchElementException e) {
// If the channel is in the process of closing but not yet closed, some handlers could have
// been removed and would cause NoSuchElement exceptions to be thrown. Because handlers are
// removed in reverse-order, if we get a NoSuchElement exception, the following handlers
// should have been removed.
}
}
channelPool.release(ch);
}
public static Bootstrap createNettyHttpClientBootstrap() {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
p.addLast("clientResponseHandler", new SimpleChannelInboundHandler<HttpObject>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
throw new RuntimeException("Client response handler was not setup before the call");
}
});
}
});
return bootstrap;
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
// Enable HTTPS if necessary.
// if (sslCtx != null) {
// pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// }
pipeline.addLast(new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast(new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpContents.
//pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new HttpObjectAggregator(65536 * 3));
// pipeline.addLast(new HttpClientHandler(null, mHttpClientListener));
}
/**
* {@link Provides} the list of providers of {@link ChannelHandler}s that are used for https
* protocol.
*/
@Provides
@HttpsWhoisProtocol
static ImmutableList<Provider<? extends ChannelHandler>> providerHttpsWhoisHandlerProviders(
@HttpsWhoisProtocol
Provider<SslClientInitializer<NioSocketChannel>> sslClientInitializerProvider,
Provider<HttpClientCodec> httpClientCodecProvider,
Provider<HttpObjectAggregator> httpObjectAggregatorProvider,
Provider<WebWhoisMessageHandler> messageHandlerProvider,
Provider<WebWhoisActionHandler> webWhoisActionHandlerProvider) {
return ImmutableList.of(
sslClientInitializerProvider,
httpClientCodecProvider,
httpObjectAggregatorProvider,
messageHandlerProvider,
webWhoisActionHandlerProvider);
}
@Provides
@HttpsRelayProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
@HttpsRelayProtocol
Provider<SslClientInitializer<NioSocketChannel>> sslClientInitializerProvider,
Provider<HttpClientCodec> httpClientCodecProvider,
Provider<HttpObjectAggregator> httpObjectAggregatorProvider,
Provider<BackendMetricsHandler> backendMetricsHandlerProvider,
Provider<LoggingHandler> loggingHandlerProvider,
Provider<FullHttpResponseRelayHandler> relayHandlerProvider) {
return ImmutableList.of(
sslClientInitializerProvider,
httpClientCodecProvider,
httpObjectAggregatorProvider,
backendMetricsHandlerProvider,
loggingHandlerProvider,
relayHandlerProvider);
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast("ssl", sslCtx.newHandler(ch.alloc()));
}
pipeline.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
pipeline.addLast("inflater", new HttpContentDecompressor());
// to be used since huge file transfer
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new HttpUploadClientHandler());
}
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
// Enable HTTPS if necessary.
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression.
p.addLast(new HttpContentDecompressor());
// Uncomment the following line if you don't want to handle HttpContents.
//p.addLast(new HttpObjectAggregator(1048576));
p.addLast(new HttpSnoopClientHandler());
}
@Override
protected ChannelInitializer<SocketChannel> getChannelInitializer() {
return new ChannelInitializer<SocketChannel> () {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
}
p.addLast(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
handler,
new MessageDecoder(new GlobalStats(),
new Limits(new ServerProperties(Collections.emptyMap())))
);
}
};
}
@Override
public ChannelInitializer<SocketChannel> getChannelInitializer() {
return new ChannelInitializer<SocketChannel> () {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(
sslCtx.newHandler(ch.alloc(), host, port),
new HttpClientCodec(),
new HttpObjectAggregator(8192),
appHandler,
new WSMessageDecoder(new GlobalStats(),
new Limits(new ServerProperties(Collections.emptyMap()))
)
);
}
};
}
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
// Register the plaintext upgrader
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(handler);
HttpClientCodec httpClientCodec = new HttpClientCodec();
final HttpClientUpgradeHandler upgrader =
new HttpClientUpgradeHandler(httpClientCodec, upgradeCodec, 1000);
return new BufferingHttp2UpgradeHandler(upgrader, handler);
}
/**
* http协议支持
*/
private void appendHttpCodec(ChannelPipeline pipeline) {
// http支持 webSocket是建立在http上的
pipeline.addLast(new HttpClientCodec());
// http请求和响应可能被分段,利用聚合器将http请求合并为完整的Http请求
pipeline.addLast(new HttpObjectAggregator(65535));
}
public static Channel connect(
boolean management, ConfigManager configManager, int readTimeOut) {
Logger logger = LoggerFactory.getLogger(ModelServerTest.class);
final Connector connector = configManager.getListener(management);
try {
Bootstrap b = new Bootstrap();
final SslContext sslCtx =
SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
b.group(Connector.newEventLoopGroup(1))
.channel(connector.getClientChannel())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(
new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) {
ChannelPipeline p = ch.pipeline();
if (connector.isSsl()) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new ReadTimeoutHandler(readTimeOut));
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpObjectAggregator(6553600));
p.addLast(new TestHandler());
}
});
return b.connect(connector.getSocketAddress()).sync().channel();
} catch (Throwable t) {
logger.warn("Connect error.", t);
}
return null;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc(), this.uri.getHost(), this.port));
}
pipeline.addLast(new IdleStateHandler(IDLE_TIMEOUT_SECONDS, IDLE_TIMEOUT_SECONDS, IDLE_TIMEOUT_SECONDS));
pipeline.addLast(new HttpIdleStateHandler());
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(maxResponseSize));
pipeline.addLast(new HttpClientHandler());
}
/**
* Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
*/
private void configureClearText(SocketChannel ch) {
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ch.pipeline().addLast(sourceCodec,
upgradeHandler,
new UpgradeRequestHandler(),
new UserEventLogger());
}
private static EmbeddedChannel createClientChannel(ChannelHandler handler) throws Exception {
return new EmbeddedChannel(
new HttpClientCodec(),
new HttpObjectAggregator(8192),
new WebSocketClientProtocolHandler(new URI("ws://localhost:1234/test"),
WebSocketVersion.V13, "test-proto-2",
false, null, 65536),
handler);
}
public static void pipelineAddExit(final Object thiz, final Object arg2) {
final ChannelPipeline pipeline = (ChannelPipeline)thiz;
final ChannelHandler handler = (ChannelHandler)arg2;
try {
// Server
if (handler instanceof HttpServerCodec) {
pipeline.addLast(TracingHttpServerHandler.class.getName(), new TracingHttpServerHandler());
}
else if (handler instanceof HttpRequestDecoder) {
pipeline.addLast(TracingServerChannelInboundHandlerAdapter.class.getName(), new TracingServerChannelInboundHandlerAdapter());
}
else if (handler instanceof HttpResponseEncoder) {
pipeline.addLast(TracingServerChannelOutboundHandlerAdapter.class.getName(), new TracingServerChannelOutboundHandlerAdapter());
}
else
// Client
if (handler instanceof HttpClientCodec) {
pipeline.addLast(TracingHttpClientTracingHandler.class.getName(), new TracingHttpClientTracingHandler());
}
else if (handler instanceof HttpRequestEncoder) {
pipeline.addLast(TracingClientChannelOutboundHandlerAdapter.class.getName(), new TracingClientChannelOutboundHandlerAdapter());
}
else if (handler instanceof HttpResponseDecoder) {
pipeline.addLast(TracingClientChannelInboundHandlerAdapter.class.getName(), new TracingClientChannelInboundHandlerAdapter());
}
}
catch (final IllegalArgumentException ignore) {
}
}
public ClientJSONPoint(URI uri) throws SSLException {
this.uri = uri;
String protocol = uri.getScheme();
if (!"ws".equals(protocol) && !"wss".equals(protocol)) {
throw new IllegalArgumentException("Unsupported protocol: " + protocol);
}
if ("wss".equals(protocol)) {
ssl = true;
}
if (uri.getPort() == -1) {
if ("ws".equals(protocol)) port = 80;
else port = 443;
} else port = uri.getPort();
final SslContext sslCtx;
if (ssl) {
sslCtx = SslContextBuilder.forClient().build();
} else sslCtx = null;
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline pipeline = ch.pipeline();
if (sslCtx != null) {
pipeline.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), port));
}
pipeline.addLast("http-codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("ws-handler", webSocketClientHandler);
}
});
}
private ChannelFuture establishConnection(URL url, EventLoop loop) {
String host = url.getHost();
int port = url.getPort();
boolean ssl = url.getProtocol().equals("https");
if (port == -1) {
port = ssl ? 443 : 80;
}
InetSocketAddress address = InetSocketAddress.createUnresolved(host, port);
return server.initializeGenericBootstrap(loop)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
if (ssl) {
SslContext context = SslContextBuilder.forClient().protocols("TLSv1.2").build();
// Unbelievably, Java doesn't automatically check the CN to make sure we're talking
// to the right host! Therefore, we provide the intended host name and port, along
// with asking Java very nicely if it could check the hostname in the certificate
// for us.
SSLEngine engine = context.newEngine(ch.alloc(), address.getHostString(),
address.getPort());
engine.getSSLParameters().setEndpointIdentificationAlgorithm("HTTPS");
ch.pipeline().addLast("ssl", new SslHandler(engine));
}
ch.pipeline().addLast("http", new HttpClientCodec());
}
})
.connect(address);
}
/**
* Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
*/
private void configureClearText(SocketChannel ch) {
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ch.pipeline().addLast(sourceCodec,
upgradeHandler,
new UpgradeRequestHandler(),
new UserEventLogger());
}
/**
* Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
*/
private void configureClearTextWithHttpUpgrade(SocketChannel ch) {
HttpClientCodec sourceCodec = new HttpClientCodec();
Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
ch.pipeline().addLast(sourceCodec, upgradeHandler, new UpgradeRequestHandler(), new UserEventLogger());
}