如何将异步HTTP请求响应组合到一个?

时间:2013-03-28 08:08:08

标签: java asynchronous

我正在尝试异步发出x个HTTP请求。我查看了问题Asynchronous IO in Java?How do you create an asynchronous HTTP request in JAVA?。我找到了很好的库Asynchronous Http and WebSocket Client library for Java,但我不明白如何安全地将多个结果组合成一个结果。例如,如果我有以下代码:

AsyncHttpClient c = new AsyncHttpClient();
List<String> urls = getUrls();
List<MyResultObject> results = new ArrayList<>();
for(String url : urls)
{
    // Create asynchronous request
    Future<MyResultObject> f = c.prepareGet(url).execute(handler);

    // How can I add completed responses to my results list ???
}

如何安全地将这些结果组合到List中,并在所有请求完成后继续。

3 个答案:

答案 0 :(得分:2)

我发现this tutorial使用期货。您可以执行以下操作:

AsyncHttpClient c = new AsyncHttpClient();
List<String> urls = getUrls();
List<Future<MyResultObject>> futures = new ArrayList<>();  // keep track of your futures
List<MyResultObject> results = new ArrayList<>();
for(String url : urls)
{
    // Create asynchronous request
    Future<MyResultObject> f = c.prepareGet(url).execute(handler);
    futures.add(f);
}

// Now retrieve the result
for (Future<MyResultObject> future : futures) {
  try {
    results.add(future.get());
  } catch (InterruptedException e) {
    e.printStackTrace();
  } catch (ExecutionException e) {
    e.printStackTrace();
  }
}
// continue with your result list

答案 1 :(得分:0)

您可以调用Future类的get()方法来获取结果。请注意,对方法的调用可能会阻塞,直到结果可用

答案 2 :(得分:0)

如果你想要组合几个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());
            }
        }
    }
}