有人可以指我制作并行网络请求的代码段吗?我需要发出6个Web请求并连接HTML结果。
有没有快速的方法来实现这一点,还是我必须采用线程方式?
谢谢。
答案 0 :(得分:4)
将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();
与
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();
}
}
答案 1 :(得分:1)
我建议您了解java.util.concurrent.ExecutorService。它允许您同时运行任务,并且适用于您描述的场景。