【问题标题】:How would I create parallel HTTP GET requests in Java [duplicate]我将如何在 Java 中创建并行 HTTP GET 请求 [重复]
【发布时间】:2021-08-29 13:00:01
【问题描述】:

首先,我应该指出,我对 Java 还很陌生,所以对这个主题进行研究有相当长的学习曲线,而且我几乎不明白我在读什么。我的预期目标是发送多个 HTTP GET 请求(约 60 个),然后在合理的时间范围内将所有数据组合成一个 JSONObject。

我已经成功完成了部分任务(尽管我的方法可能是非正统的),但是它是同步的,这让我等待了很长时间才收到我的回复,这不是我想要实现的目标。

如果有人能提供一些关于我如何解决这个问题的见解,那将有很大帮助,以及我可以在哪里了解更多关于正在使用的部件的信息。

    private static int pages;
    private static final String BASE = "https://someapi.com/api?page=";

    public static String getData() throws IOException {
        JSONObject finalData = new JSONObject();

        System.out.println("Attempting to get API data!");
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(
                BASE + "0");
        HttpResponse response = client.execute(request);

        String result = IOUtils.toString(new BufferedReader
                (new InputStreamReader(
                        response.getEntity().getContent())));
    
        JSONObject jsonData = new JSONObject(result);
        pages = jsonData.getInt("totalPages");
        totalData.put("0", jsonData.getJSONArray("data"));
        for (int x = 1; x < pages; x++) {
            totalData.put(Integer.toString(x), getPageData(x)); // getPageData is essentially a copy-paste of the HTTP client except it has a different number being added to the paste.
        }
        return totalData.toString();
    }

【问题讨论】:

  • 您可能想看看Future 和/或公开异步 API 的 http 库
  • 主要答案确实回答了我的问题,但是我无法让它工作。关于第二个答案 async-http-client,我不确定如何根据它的示例使用它来满足我的需求。

标签: java


【解决方案1】:

你可以创建多个线程,每个线程负责一个请求

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多