在 Java 中同时发出 Web 请求

Mri*_*lla 3 java concurrency multithreading

有人可以指出我进行并行网络请求的片段吗?我需要发出 6 个 Web 请求并连接 HTML 结果。

有没有一种快速的方法来完成这个,还是我必须走线程的方式?

谢谢你。

Bal*_*usC 6

ExecutorService与 一起使用Callable<InputStream>

开场示例:

ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
Future<InputStream> response1 = executor.submit(new Request("http://google.com"));
Future<InputStream> response2 = executor.submit(new Request("http://stackoverflow.com"));
// ...
ByteArrayOutputStream totalResponse = new ByteArrayOutputStream();
copyAndCloseInput(response1.get(), totalResponse);
copyAndCloseInput(response2.get(), totalResponse);
// ...
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)

public class Request implements Callable<InputStream> {

    private String url;

    public Request(String url) {
        this.url = url;
    }

    @Override
    public InputStream call() throws Exception {
        return new URL(url).openStream();
    }

}
Run Code Online (Sandbox Code Playgroud)

也可以看看: