我需要发出大约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());
}
});
}
}
1条答案
按热度按时间83qze16e1#
看起来你的例子根本不是异步的。看下面的例子https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/asynchronousget.java 试试看。
具体来说,您应该调用enqueue而不是execute。