Вопрос

I am getting 302 status code for the http request I am making to my URL.. I want it to be handled by my netty code..

My client code :

      public static void main(String[] args) throws Exception {
           URI uri = new URI("http://myurl.mydomain.com/v1/v2?param1=value1&param2=value2");           
           String host = uri.getHost();
            int port = 80;

         // Configure the client.
            EventLoopGroup group = new NioEventLoopGroup();
            try {
                Bootstrap b = new Bootstrap();
                b.group(group)
                 .channel(NioSocketChannel.class)
                 .handler(new NettyClientInitializer());
                // Make the connection attempt.
                Channel ch = b.connect(host, port).sync().channel();
                // Prepare the HTTP request.
                HttpRequest request = new DefaultHttpRequest(
                        HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toString());
                request.headers().set(HttpHeaders.Names.HOST, host);
                request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);  
                request.headers().set(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.NO_CACHE);

                /*// Set some example cookies.
                request.headers().set(
                        HttpHeaders.Names.COOKIE,
                        ClientCookieEncoder.encode(
                                new DefaultCookie("my-cookie", "foo"),
                                new DefaultCookie("another-cookie", "bar")));
*/
                // Send the HTTP request.
                ch.writeAndFlush(request);

                // Wait for the server to close the connection.
                ch.closeFuture().sync();
            } finally {
                // Shut down executor threads to exit.
                group.shutdownGracefully();
            }
      }

My handler code :

public class NettyClientHandler extends SimpleChannelInboundHandler<HttpObject> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;

            System.out.println("STATUS: " + response.getStatus());
            System.out.println("VERSION: " + response.getProtocolVersion());
            System.out.println();

            if (!response.headers().isEmpty()) {
                for (String name: response.headers().names()) {
                    for (String value: response.headers().getAll(name)) {
                        System.out.println("HEADER: " + name + " = " + value);
                    }
                }
                System.out.println();
            }

            if (HttpHeaders.isTransferEncodingChunked(response)) {
                System.out.println("CHUNKED CONTENT {");
            } else {
                System.out.println("CONTENT {");
            }
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;

            System.out.print(content.content().toString(CharsetUtil.UTF_8));
            System.out.flush();

            if (content instanceof LastHttpContent) {
                System.out.println("} END OF CONTENT");
            }
        }
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }


}

My initializer code :

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        // Create a default pipeline implementation.
        ChannelPipeline p = ch.pipeline();

        p.addLast("log", new LoggingHandler(LogLevel.INFO));
        // Enable HTTPS if necessary.
        /*
        if (ssl) {
            SSLEngine engine =
                SecureChatSslContextFactory.getClientContext().createSSLEngine();
            engine.setUseClientMode(true);

            p.addLast("ssl", new SslHandler(engine));
        }
*/
        p.addLast("codec", new HttpClientCodec());

        // Remove the following line if you don't want automatic content decompression.
       // p.addLast("inflater", new HttpContentDecompressor());

        // Uncomment the following line if you don't want to handle HttpChunks.
        p.addLast("aggregator", new HttpObjectAggregator(1048576));       
        p.addLast("handler", new NettyClientHandler());

    }
}

I referred to this link with similar problem : redirect - handling http 302 moved temporarily using netty

but the code in this using 3.x version of the library and also there is no answer to this question as of now..

I am using Netty 4.0.12 library..

Please tell me how to handle this using Netty

Это было полезно?

Решение

You can modify your NettyClientHandler to check for 302 Redirects, and open a new connection to handle the HTML content of the redirect.

Changes made to NettyClientHandler:

//We know this is a redirect...
            if(response.getStatus().code() == HttpResponseStatus.FOUND.code()){//When its a 302...

                if(response.headers().names().contains("Location"))
                {
                    System.out.println("We have a redirect...");
                    //Now we will do the process over to get the actual content...
                    Main.main(new String[]{response.headers().get("Location")});
                }
            }

Changes made to main() as an example to handle the content of the redirect:

String urlPlace = "http://initial.com";

        if(args != null && args.length > 0)
        {
            urlPlace = args[0];
        }

        URI uri = new URI(urlPlace);
        String host = uri.getHost();
        int port = uri.getPort();
        if(port == -1)
        {
            port = 80;
        }

When we get a HTTP Status code 302, it is the "servers" responsibility to set the Location header for the new URL location in order for the client to handle appropriately.

See Wikipedia 302

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top