Last Updated: September 13, 2016
·
968
· groodt

Using RxNetty TLS/SSL HttpClient securely

If you would like to use RxNetty for secure reactive HTTP against hosts on the public internet, see the example here

This is example is for RxNetty 0.5.x

public final class SecureDefaultHttpClient {

    private final static String HOST = "github.com";
    private final static Integer PORT = 443;

    public static void main(String[] args) {

        ExamplesEnvironment env = ExamplesEnvironment.newEnvironment(SecureDefaultHttpClient.class);
        Logger logger = env.getLogger();

        SSLEngine sslEngine = null;
        try {
            sslEngine = defaultSSLEngineForClient();
        } catch (NoSuchAlgorithmException nsae) {
            logger.error("Failed to create SSLEngine.", nsae);
            System.exit(-1);
        }

        HttpClient.newClient(HOST, PORT)
                .enableWireLogging("http-secure-default-client", LogLevel.DEBUG)
                .secure(sslEngine)
                .createGet("/")
                .doOnNext(resp -> logger.info(resp.toString()))
                .flatMap(resp -> {
                            System.out.println(resp.getStatus());
                            return resp.getContent()
                                    .map(bb -> bb.toString(Charset.defaultCharset()));
                        }
                )
                .toBlocking()
                .forEach(logger::info);
    }

    private static SSLEngine defaultSSLEngineForClient() throws NoSuchAlgorithmException {
        SSLContext sslCtx = SSLContext.getDefault();
        SSLEngine sslEngine = sslCtx.createSSLEngine(HOST, PORT);
        sslEngine.setUseClientMode(true);
        return sslEngine;
    }
}