【问题标题】:The speed does not change from an asynchronous request速度不会因异步请求而改变
【发布时间】:2021-03-28 23:28:48
【问题描述】:

我需要发出大约 60 个 HTTP 请求。

第一种情况,我没有使用异步请求,速度大约是1.5分钟。 第二种情况,我用的是异步请求,速度也没有变化,大概1.5分钟左右。

请看我的代码。也许我没有正确执行异步请求,或者是否有其他方法可以快速发出大量 HTTP 请求?

public class Main {

    public static int page = 0;

    public static void main(String[] args) throws IOException {
        int totalPages = Util.getTotalPages();

        page = 0;
        while(page < totalPages) {
            // Function does not work
            new GetAuctions();
            page++;
        }
    }
}
public class Util {
    public static final String API_KEY = "***";
    public static final OkHttpClient httpClient = new OkHttpClient();
    public static final List<JSONObject> auctions = new ArrayList<>();

    public static int getTotalPages() throws IOException {
        Request request = new Request.Builder().url("https://api.hypixel.net/skyblock/auctions?key=" + Util.API_KEY + "&page=0").build();

        Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) throw new IOException("Error: " + response);

        assert response.body() != null;
        String jsonData = response.body().string();

        JSONObject object = new JSONObject(jsonData);

        return object.getInt("totalPages");
    }
}
public class GetAuctions {

    public static void main(String[] args) throws Exception {
        new GetAuctions().run();
    }

    public void run() throws Exception {
        Request request = new Request.Builder().url("https://api.hypixel.net/skyblock/auctions?key=" + Util.API_KEY + "&page=" + Main.page).build();

        Util.httpClient.newCall(request).enqueue(new Callback() {
            @Override public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                assert response.body() != null;
                String jsonData = response.body().string();

                JSONObject object = new JSONObject(jsonData);
                JSONArray array = object.getJSONArray("auctions");

                for (int i=0; i<array.length(); i++) {
                    JSONObject jsonObject = array.getJSONObject(i);

                    if (jsonObject.has("bin")) {
                        Util.auctions.add(jsonObject);
                    }
                }

                System.out.println(Util.auctions.size());
            }
        });
    }
}

【问题讨论】:

  • 我在您的代码中看不到一个异步调用。您基本上在 GetAuctions 类中创建了一个 run 方法,并在每次在 while 循环中创建新方法时调用它。

标签: java http asynchronous request okhttp


【解决方案1】:

看起来您的示例根本不是异步的。查看https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AsynchronousGet.java 中的示例并尝试使用它。

具体来说,您应该调用 enqueue 而不是 execute。

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        e.printStackTrace();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try (ResponseBody responseBody = response.body()) {
          if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

          Headers responseHeaders = response.headers();
          for (int i = 0, size = responseHeaders.size(); i < size; i++) {
            System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
          }

          System.out.println(responseBody.string());
        }
      }
    });
  }

【讨论】:

  • 你好,尤里!我听取了您的建议,并在 Internet 上搜索了很多有关异步请求的信息。现在我已经完全重新设计了 GetActions 类。你能看出错误是什么吗?速度没变。 (mkyong.com/java/java-11-httpclient-examples)
  • 你最新的例子是使用 JDK11 Http Client 而不是 OkHttp。我建议选择您喜欢的任何一个,但我能做的最多就是帮助您使用我已经为 OkHttp 提供的链接。对不起。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多