本文整理汇总了Java中io.netty.handler.codec.http.HttpRequestEncoder类的典型用法代码示例。如果您正苦于以下问题:Java HttpRequestEncoder类的具体用法?Java HttpRequestEncoder怎么用?Java HttpRequestEncoder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpRequestEncoder类属于io.netty.handler.codec.http包,在下文中一共展示了HttpRequestEncoder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doStart
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
protected void doStart(Listener listener) throws Throwable {
workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.option(ChannelOption.TCP_NODELAY, true);
b.option(ChannelOption.SO_REUSEADDR, true);
b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("decoder", new HttpResponseDecoder());
ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
ch.pipeline().addLast("encoder", new HttpRequestEncoder());
ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
}
});
timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
listener.onSuccess();
}
示例2: configNewChannel
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
public void configNewChannel(NioSocketChannel channel) {
super.configNewChannel(channel);
ChannelPipeline pipeline = channel.pipeline();
// 添加 SSL 数据支持
if (requestConfig.https()) {
SslContext sslContent = NettyCenter.singleInstance().getSimpleClientSslContext();
SSLEngine engine = sslContent.newEngine(channel.alloc());
pipeline.addLast("ssl", new SslHandler(engine));
}
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
pipeline.addLast("decoder", new HttpResponseDecoder());
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
pipeline.addLast("encoder", new HttpRequestEncoder());
// 接收的请求累计器
pipeline.addLast("aggegator", new HttpObjectAggregator(0x30000));
// mime 类型写出
pipeline.addLast("streamew", new ChunkedWriteHandler());
// 添加解压器
pipeline.addLast("decompressor", new HttpContentDecompressor());
// add new handler
pipeline.addLast("handler", new NettyHttpRequestChannelHandler());
}
示例3: initChannel
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
protected void initChannel(SocketChannel ch) throws Exception {
// Add the generic handlers to the pipeline
// e.g. SSL handler
if (sslEngine != null) {
if (log.isDebugEnabled()) {
log.debug("adding ssl handler");
}
ch.pipeline().addLast("ssl", new SslHandler(this.sslEngine));
}
ch.pipeline().addLast("compressor", new HttpContentCompressor());
ch.pipeline().addLast("decoder", new HttpResponseDecoder());
ch.pipeline().addLast("encoder", new HttpRequestEncoder());
if (httpTraceLogEnabled) {
ch.pipeline().addLast(Constants.HTTP_TRACE_LOG_HANDLER,
new HTTPTraceLoggingHandler("tracelog.http.upstream", LogLevel.DEBUG));
}
RedirectHandler redirectHandler = new RedirectHandler(sslEngine, httpTraceLogEnabled, maxRedirectCount
, chunkDisabled, originalChannelContext, isIdleHandlerOfTargetChannelRemoved);
ch.pipeline().addLast(Constants.REDIRECT_HANDLER, redirectHandler);
}
示例4: unitTestForRedirectHandler
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
/**
* Check whether, redirect request is written to the backend when a redirect response is received.
*
* @throws URISyntaxException
* @throws IOException
*/
@Test
public void unitTestForRedirectHandler() throws URISyntaxException, IOException {
EmbeddedChannel embeddedChannel = new EmbeddedChannel();
embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false));
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
Unpooled.EMPTY_BUFFER);
response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
.set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
embeddedChannel.writeInbound(response);
embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
assertNotNull(embeddedChannel.readOutbound());
}
示例5: unitTestForRedirectLoop
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
/**
* When the maximum redirect count reached, channel should not do any more redirects.
*
* @throws URISyntaxException
* @throws IOException
*/
@Test
public void unitTestForRedirectLoop() throws URISyntaxException, IOException {
EmbeddedChannel embeddedChannel = new EmbeddedChannel();
embeddedChannel.pipeline().addLast(new HttpResponseDecoder());
embeddedChannel.pipeline().addLast(new HttpRequestEncoder());
embeddedChannel.pipeline()
.addLast(Constants.IDLE_STATE_HANDLER, new IdleStateHandler(50000, 50000, 0, TimeUnit.MILLISECONDS));
embeddedChannel.pipeline().addLast(new RedirectHandler(null, false, 5, false, null, false));
HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT,
Unpooled.EMPTY_BUFFER);
response.headers().set(HttpHeaders.Names.LOCATION, FINAL_DESTINATION);
embeddedChannel.attr(Constants.ORIGINAL_REQUEST)
.set(createHttpRequest(Constants.HTTP_GET_METHOD, FINAL_DESTINATION));
embeddedChannel.attr(Constants.RESPONSE_FUTURE_OF_ORIGINAL_CHANNEL).set(new HttpResponseFutureImpl());
TargetChannel targetChannel = new TargetChannel(null, null);
targetChannel.setChannel(embeddedChannel);
embeddedChannel.attr(Constants.TARGET_CHANNEL_REFERENCE).set(targetChannel);
embeddedChannel.attr(Constants.REDIRECT_COUNT).set(5);
embeddedChannel.writeInbound(response);
embeddedChannel.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT);
assertNull(embeddedChannel.readOutbound());
}
示例6: initChannel
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if(directWriteBack) {
p.addLast("encoder", new HttpRequestEncoder());
p.addLast(new DirectWriteBackHttpProxyBackendHandler(inboundCtx.channel()));
} else {
p.addLast("encoder", new HttpRequestEncoder());
p.addLast("decoder", new HttpResponseDecoder());
//p.addLast("aggregator", new HttpObjectAggregator(2048));
p.addLast(new HttpProxyBackendHandler(inboundCtx, index));
}
}
示例7: initChannel
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
if(sslCtx!=null)
{
p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
}
p.addLast(new HttpResponseDecoder());
//限制contentLength
p.addLast(new HttpObjectAggregator(65536));
p.addLast(new HttpRequestEncoder());
//大文件传输处理
// p.addLast(new ChunkedWriteHandler());
p.addLast(new DefaultListenerHandler<HttpResponse>(listener));
}
示例8: Bootstrap
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
public void channelRead0
(final ChannelHandlerContext ctx, final HttpRequest req) {
uri = req.getUri();
final Channel client = ctx.channel();
Bootstrap proxiedServer = new Bootstrap()
.group(client.eventLoop())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
}
});
ChannelFuture f = proxiedServer.connect(host);
proxiedChannel = f.channel();
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ctx.channel().pipeline().remove(HttpResponseEncoder.class);
HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
req.getMethod(), req.getUri());
newReq.headers().add(req.headers());
newReq.headers().set(CONNECTION, Values.CLOSE);
future.channel().writeAndFlush(newReq);
} else {
DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
INTERNAL_SERVER_ERROR);
resp.headers().set(CONNECTION, Values.CLOSE);
LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
client.close();
}
}
});
}
示例9: Bootstrap
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
@Override
public void channelRead0
(final ChannelHandlerContext ctx, final HttpRequest req) {
uri = req.uri();
final Channel client = ctx.channel();
Bootstrap proxiedServer = new Bootstrap()
.group(client.eventLoop())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
}
});
ChannelFuture f = proxiedServer.connect(host);
proxiedChannel = f.channel();
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ctx.channel().pipeline().remove(HttpResponseEncoder.class);
HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
req.method(), req.uri());
newReq.headers().add(req.headers());
newReq.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
future.channel().writeAndFlush(newReq);
} else {
DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
INTERNAL_SERVER_ERROR);
resp.headers().set(CONNECTION, HttpHeaderValues.CLOSE);
LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
client.close();
}
}
});
}
示例10: connect
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
public void connect(String host, int port) throws Exception {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
// 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
ch.pipeline().addLast(new HttpResponseDecoder());
// 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
ch.pipeline().addLast(new HttpRequestEncoder());
ch.pipeline().addLast(new HttpClientInboundHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(host, port).sync();
URI uri = new URI("http://127.0.0.1:8844");
String msg = "Are you ok?";
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));
// 构建http请求
request.headers().set(HttpHeaders.Names.HOST, host);
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, request.content().readableBytes());
// 发送http请求
f.channel().write(request);
f.channel().flush();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
示例11: determineHttpClientCodecOutboundState
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
protected static int determineHttpClientCodecOutboundState(HttpClientCodec currentCodec) {
try {
HttpRequestEncoder encoder = (HttpRequestEncoder) httpClientCodecOutboundHandlerField.get(currentCodec);
return httpObjectEncoderStateField.getInt(encoder);
}
catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
示例12: connect
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
public void connect(int port) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast("http-decoder",
new HttpResponseDecoder());
ch.pipeline().addLast("http-aggregator",
new HttpObjectAggregator(65536));
// XML解码器
ch.pipeline().addLast(
"xml-decoder",
new HttpXmlResponseDecoder(Order.class,
true));
ch.pipeline().addLast("http-encoder",
new HttpRequestEncoder());
ch.pipeline().addLast("xml-encoder",
new HttpXmlRequestEncoder());
ch.pipeline().addLast("xmlClientHandler",
new HttpXmlClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();
// 当代客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
示例13: ProxyClient
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
public ProxyClient(String address, final EventLoop loop) {
super(address, loop);
codec(new CodecInitializer() {
@Override
public void initPipeline(List<ChannelHandler> p) {
p.add(new HttpRequestEncoder());
p.add(new HttpResponseDecoder());
p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
p.add(new MessageCodec());
}
});
onDisconnected(new DisconnectedHandler() {
@Override
public void onDisconnected() throws IOException {
log.info("Disconnected from(%s) ID=%s", serverAddress(), clientId);
ProxyClient.this.close();
}
});
onError(new ErrorHandler() {
@Override
public void onError(Throwable e, Session session) throws IOException {
ProxyClient.this.close();
}
});
}
示例14: initSupport
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
protected void initSupport(ServerAddress address, final EventLoop loop){
if(address.getServer() != null){
support = new InProcClient<Message, Message>(address.getServer().getIoAdaptor());
return;
}
TcpClient<Message, Message> tcp = new TcpClient<Message, Message>(address, loop);
support = tcp;
tcp.codec(new CodecInitializer() {
@Override
public void initPipeline(List<ChannelHandler> p) {
p.add(new HttpRequestEncoder());
p.add(new HttpResponseDecoder());
p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
p.add(new MessageCodec());
}
});
tcp.startHeartbeat(heartbeatInterval, new HeartbeatMessageBuilder<Message>() {
@Override
public Message build() {
Message hbt = new Message();
hbt.setCommand(Message.HEARTBEAT);
return hbt;
}
});
}
示例15: initChannelPipeline
import io.netty.handler.codec.http.HttpRequestEncoder; //导入依赖的package包/类
/**
* Initialize our {@link ChannelPipeline}.
*
* @param pipeline
* @param httpRequest
*/
private void initChannelPipeline(ChannelPipeline pipeline,
HttpRequest httpRequest) {
if (trafficHandler != null) {
pipeline.addLast("global-traffic-shaping", trafficHandler);
}
pipeline.addLast("bytesReadMonitor", bytesReadMonitor);
pipeline.addLast("decoder", new HeadAwareHttpResponseDecoder(
8192,
8192 * 2,
8192 * 2));
pipeline.addLast("responseReadMonitor", responseReadMonitor);
// Enable aggregation for filtering if necessary
int numberOfBytesToBuffer = proxyServer.getFiltersSource()
.getMaximumResponseBufferSizeInBytes();
if (numberOfBytesToBuffer > 0) {
aggregateContentForFiltering(pipeline, numberOfBytesToBuffer);
}
pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor);
pipeline.addLast("encoder", new HttpRequestEncoder());
pipeline.addLast("requestWrittenMonitor", requestWrittenMonitor);
// Set idle timeout
pipeline.addLast(
"idle",
new IdleStateHandler(0, 0, proxyServer
.getIdleConnectionTimeout()));
pipeline.addLast("handler", this);
}