SOCKS 代理请求

在某些场景下,如业务需求通过SOCKS代理发送到对端服务时,需要走SOCKS代理才能发送,那么便可以采用Proxy代理来发送请求。

代码示例

@Test
public void testRxIoHttpProxy() throws Exception {
    final EventLoopGroup group = new EventLoopGroup(4);
    group.start();

    CountDownLatch latch = new CountDownLatch(1);
    final String url = "http://myip.ipip.net";
    RxIo.create(new OnSubscribeIo<HttpAnswer>(group, new IoHttp(url)))
            .request(new IoFunction<HttpAnswer, RxIo<HttpAnswer>>() {
                @Override
                public RxIo<HttpAnswer> call(HttpAnswer response) throws Exception {
                    System.err.println("----------------- " + Thread.currentThread() + url + " ----------------");
                    System.out.println(response.getContent());
                    // 配置代理IP和端口
                    InetSocketAddress proxyAddr = new InetSocketAddress("代理IP", 代理端口);
                    Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
                    // 发送代理请求
                    return RxIo.create(group, new IoHttp(url, proxy));
                }
            })
            .subscribe(new IoSubscriber<HttpAnswer>() {
                @Override
                public void onNext(HttpAnswer response) throws IOException {
                    System.err.println("----------------- " + Thread.currentThread() + url + " ----------------");
                    System.out.println(response.getContent());
                }

                @Override
                public void onCompleted() {
                    System.out.println("execute complete");
                    latch.countDown();
                    group.shutdown();
                }

                @Override
                public void onError(Throwable e) {
                    System.err.println("exception caught");
                    e.printStackTrace();
                }
            }).start();
    latch.await();
}