如果你想合并几个http请求并获得所有结果。你可以看看代码打击。
package ParallelTasks;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ParallelHttpRequest {
//thread pool to execute http request task.
static final ExecutorService businessRequestExecutor = Executors.newCachedThreadPool();
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<String> urlList = new ArrayList<String>();
final CountDownLatch latch = new CountDownLatch(urlList.size());
List<Future<Pair<String, String>>> list = new ArrayList<Future<Pair<String, String>>>();
for (final String url : urlList) {
Future<Pair<String, String>> future = businessRequestExecutor.submit(new Callable<Pair<String, String>>() {
public Pair<String, String> call() throws Exception {
try {
//do post or get http request here.
//SoaHttpUtil.post(config.getUrl(), buReqJson);
String result = "";
return new MutablePair<String, String>(url, result);
} catch (Exception ex) {
System.out.println(ex);
return new MutablePair<String, String>(url, null);
} finally {
latch.countDown();
}
}
});
list.add(future);
}
//wait no more than 5 seconds.
latch.await(5000, TimeUnit.MILLISECONDS);
//print finished request's result.
for (Future<Pair<String, String>> future : list) {
if (future.isDone()) {
System.out.println(future.get().getValue());
}
}
}
}