Search in sources :

Example 31 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project proxyee-down by monkeyWie.

the class CookieIntercept method beforeRequest.

@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
    String acceptValue = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
    if (acceptValue != null && acceptValue.contains("application/x-sniff-cookie")) {
        HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new DefaultHttpHeaders());
        httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        // https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
        AsciiString customHeadKey = AsciiString.cached("X-Sniff-Cookie");
        String cookie = pipeline.getHttpRequest().headers().get(HttpHeaderNames.COOKIE);
        httpResponse.headers().set(customHeadKey, cookie == null ? "" : cookie);
        httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, customHeadKey);
        String origin = httpRequest.headers().get(HttpHeaderNames.ORIGIN);
        if (StringUtil.isNullOrEmpty(origin)) {
            String referer = httpRequest.headers().get(HttpHeaderNames.REFERER);
            URL url = new URL(referer);
            origin = url.getHost();
        }
        httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
        httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
        clientChannel.writeAndFlush(httpResponse);
        clientChannel.writeAndFlush(new DefaultLastHttpContent());
        clientChannel.close();
    } else {
        super.beforeRequest(clientChannel, httpRequest, pipeline);
    }
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) AsciiString(io.netty.util.AsciiString) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) AsciiString(io.netty.util.AsciiString) URL(java.net.URL)

Example 32 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project reactor-netty by reactor.

the class HttpOperationsTest method httpAndJsonDecoders.

@Test
public void httpAndJsonDecoders() {
    EmbeddedChannel channel = new EmbeddedChannel();
    NettyContext testContext = () -> channel;
    ChannelHandler handler = new JsonObjectDecoder(true);
    testContext.addHandlerLast("foo", handler);
    HttpOperations.autoAddHttpExtractor(testContext, "foo", handler);
    String json1 = "[{\"some\": 1} , {\"valu";
    String json2 = "e\": true, \"test\": 1}]";
    Object[] content = new Object[3];
    content[0] = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    content[1] = new DefaultHttpContent(Unpooled.copiedBuffer(json1, CharsetUtil.UTF_8));
    content[2] = new DefaultLastHttpContent(Unpooled.copiedBuffer(json2, CharsetUtil.UTF_8));
    channel.writeInbound(content);
    Object t = channel.readInbound();
    assertThat(t, instanceOf(HttpResponse.class));
    assertThat(t, not(instanceOf(HttpContent.class)));
    t = channel.readInbound();
    assertThat(t, instanceOf(ByteBuf.class));
    assertThat(((ByteBuf) t).toString(CharsetUtil.UTF_8), is("{\"some\": 1}"));
    ((ByteBuf) t).release();
    t = channel.readInbound();
    assertThat(t, instanceOf(ByteBuf.class));
    assertThat(((ByteBuf) t).toString(CharsetUtil.UTF_8), is("{\"value\": true, \"test\": 1}"));
    ((ByteBuf) t).release();
    t = channel.readInbound();
    assertThat(t, is(LastHttpContent.EMPTY_LAST_CONTENT));
    ((LastHttpContent) t).release();
    t = channel.readInbound();
    assertThat(t, nullValue());
}
Also used : DefaultHttpContent(io.netty.handler.codec.http.DefaultHttpContent) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandler(io.netty.channel.ChannelHandler) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) NettyContext(reactor.ipc.netty.NettyContext) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) Test(org.junit.Test)

Example 33 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project reactor-netty by reactor.

the class HttpClientOperationsTest method addNamedDecoderReplaysLastHttp.

@Test
public void addNamedDecoderReplaysLastHttp() throws Exception {
    ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
    EmbeddedChannel channel = new EmbeddedChannel();
    HttpClientOperations ops = new HttpClientOperations(channel, (response, request) -> null, handler);
    ops.addHandler("json", new JsonObjectDecoder());
    channel.writeInbound(new DefaultLastHttpContent(buf));
    assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
    Object content = channel.readInbound();
    assertThat(content, instanceOf(ByteBuf.class));
    ((ByteBuf) content).release();
    content = channel.readInbound();
    assertThat(content, instanceOf(LastHttpContent.class));
    ((LastHttpContent) content).release();
    assertThat(channel.readInbound(), nullValue());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 34 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project reactor-netty by reactor.

the class HttpClientOperationsTest method addNamedEncoderReplaysLastHttp.

@Test
public void addNamedEncoderReplaysLastHttp() throws Exception {
    ByteBuf buf = Unpooled.copiedBuffer("{\"foo\":1}", CharsetUtil.UTF_8);
    EmbeddedChannel channel = new EmbeddedChannel();
    HttpClientOperations ops = new HttpClientOperations(channel, (response, request) -> null, handler);
    ops.addHandler("json", new JsonObjectDecoder());
    channel.writeInbound(new DefaultLastHttpContent(buf));
    assertThat(channel.pipeline().names().iterator().next(), is("json$extractor"));
    Object content = channel.readInbound();
    assertThat(content, instanceOf(ByteBuf.class));
    ((ByteBuf) content).release();
    content = channel.readInbound();
    assertThat(content, instanceOf(LastHttpContent.class));
    ((LastHttpContent) content).release();
    assertThat(channel.readInbound(), nullValue());
}
Also used : DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) JsonObjectDecoder(io.netty.handler.codec.json.JsonObjectDecoder) ByteBuf(io.netty.buffer.ByteBuf) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Test(org.junit.Test)

Example 35 with DefaultLastHttpContent

use of io.netty.handler.codec.http.DefaultLastHttpContent in project proxyee-down by monkeyWie.

the class HttpDownUtil method getResponse.

/**
 * 取请求响应
 */
public static HttpResponse getResponse(HttpRequest httpRequest, ProxyConfig proxyConfig, SslContext clientSslCtx, NioEventLoopGroup loopGroup) throws Exception {
    final HttpResponse[] httpResponses = new HttpResponse[1];
    CountDownLatch cdl = new CountDownLatch(1);
    HttpRequestInfo requestInfo = (HttpRequestInfo) httpRequest;
    RequestProto requestProto = requestInfo.requestProto();
    Bootstrap bootstrap = new Bootstrap();
    // 注册线程池
    bootstrap.group(loopGroup).channel(// 使用NioSocketChannel来作为连接用的channel类
    NioSocketChannel.class).handler(new ChannelInitializer() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            if (proxyConfig != null) {
                ch.pipeline().addLast(ProxyHandleFactory.build(proxyConfig));
            }
            if (requestProto.getSsl()) {
                ch.pipeline().addLast(clientSslCtx.newHandler(ch.alloc()));
            }
            ch.pipeline().addLast("httpCodec", new HttpClientCodec());
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx0, Object msg0) throws Exception {
                    if (msg0 instanceof HttpResponse) {
                        HttpResponse httpResponse = (HttpResponse) msg0;
                        httpResponses[0] = httpResponse;
                        ctx0.channel().close();
                        cdl.countDown();
                    }
                }
            });
        }
    });
    if (proxyConfig != null) {
        // 代理服务器解析DNS和连接
        bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
    }
    ChannelFuture cf = bootstrap.connect(requestProto.getHost(), requestProto.getPort());
    cf.addListener((ChannelFutureListener) future -> {
        if (future.isSuccess()) {
            httpRequest.headers().set(HttpHeaderNames.RANGE, "bytes=0-0");
            cf.channel().writeAndFlush(httpRequest);
            if (requestInfo.content() != null) {
                HttpContent content = new DefaultLastHttpContent();
                content.content().writeBytes(requestInfo.content());
                cf.channel().writeAndFlush(content);
            }
        } else {
            cdl.countDown();
        }
    });
    cdl.await(30, TimeUnit.SECONDS);
    if (httpResponses[0] == null) {
        throw new TimeoutException("getResponse timeout");
    }
    return httpResponses[0];
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ProxyConfig(lee.study.proxyee.proxy.ProxyConfig) ProxyHandleFactory(lee.study.proxyee.proxy.ProxyHandleFactory) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) URLDecoder(java.net.URLDecoder) URL(java.net.URL) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) NoopAddressResolverGroup(io.netty.resolver.NoopAddressResolverGroup) TaskInfo(lee.study.down.model.TaskInfo) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Matcher(java.util.regex.Matcher) HttpHeadsInfo(lee.study.down.model.HttpHeadsInfo) HttpVer(lee.study.down.model.HttpRequestInfo.HttpVer) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) HttpContent(io.netty.handler.codec.http.HttpContent) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) SslContext(io.netty.handler.ssl.SslContext) MalformedURLException(java.net.MalformedURLException) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) HttpMethod(io.netty.handler.codec.http.HttpMethod) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) IOException(java.io.IOException) UUID(java.util.UUID) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Closeable(java.io.Closeable) Entry(java.util.Map.Entry) HttpResponse(io.netty.handler.codec.http.HttpResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Pattern(java.util.regex.Pattern) ProtoUtil(lee.study.proxyee.util.ProtoUtil) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpRequestInfo(lee.study.down.model.HttpRequestInfo) CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) RequestProto(lee.study.proxyee.util.ProtoUtil.RequestProto) HttpContent(io.netty.handler.codec.http.HttpContent) DefaultLastHttpContent(io.netty.handler.codec.http.DefaultLastHttpContent) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

DefaultLastHttpContent (io.netty.handler.codec.http.DefaultLastHttpContent)73 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)32 Test (org.junit.Test)27 ByteBuf (io.netty.buffer.ByteBuf)26 DefaultHttpContent (io.netty.handler.codec.http.DefaultHttpContent)26 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)24 HttpContent (io.netty.handler.codec.http.HttpContent)17 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)12 HttpRequest (io.netty.handler.codec.http.HttpRequest)12 DefaultHttpRequest (io.netty.handler.codec.http.DefaultHttpRequest)11 HttpResponse (io.netty.handler.codec.http.HttpResponse)11 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)10 Test (org.junit.jupiter.api.Test)10 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)9 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)7 Channel (io.netty.channel.Channel)6 Test (org.testng.annotations.Test)6 SessionContext (com.netflix.zuul.context.SessionContext)5 JsonObjectDecoder (io.netty.handler.codec.json.JsonObjectDecoder)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5