我需要发出大约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());
}
});
}
}
发布于 2020-12-18 10:03:42
看起来你的例子根本不是异步的。看一下来自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());
}
}
});
}
https://stackoverflow.com/questions/65354847
复制