有人可以指出我用于发出并行网络请求的片段吗?我需要发出 6 个 Web 请求并连接 HTML 结果。
有没有一种快速的方法来完成这个任务,或者我必须采用线程方式?
谢谢。
Use ExecutorService http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html with Callable<InputStream> http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Callable.html.
开球示例:
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();
with
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();
}
}
也可以看看:
- Java 教程:并发 http://download.oracle.com/javase/tutorial/essential/concurrency/index.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)