gpt4 book ai didi

java - PageSpeed API - Java 中的批处理

转载 作者:行者123 更新时间:2023-12-02 04:19:02 26 4
gpt4 key购买 nike

我在 Java 应用程序中使用 PageSpeed API。它工作正常,但由于我需要检查很多 URL,所以我需要进行一些批处理。我一直在网上和他们的文档中查找,但找不到任何有关如何执行此操作的信息。有谁知道吗?

我正在连接一个普通的 HTTP 请求,因为它比使用他们的包更快,但我认为对于批处理来说,他们的包可能更好,所以这里是我在这两种情况下使用的代码:

HTTP 请求:

String call = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + SITE + "&key=" + GOOGLE_KEY + "&strategy=" + DEVICE;

URL url = new URL(call);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(response.toString());

PageSpeed Java 包:

JsonFactory jsonFactory = new JacksonFactory();
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
httpRequest.setReadTimeout(60000); // 60 seconds
}
};

Pagespeedonline p = new Pagespeedonline.Builder(transport, jsonFactory, httpRequestInitializer).setApplicationName("APP_NAME").build();
Pagespeedonline.Pagespeedapi.Runpagespeed runpagespeed = p.pagespeedapi().runpagespeed(SITE).setKey(GOOGLE_KEY).setStrategy(DEVICE);
PagespeedApiPagespeedResponseV5 response = runpagespeed.execute();

两者都工作正常,我只需要知道如何在两者中集成批处理。

有人可以帮助我吗?

非常感谢!

最佳答案

我成功做到了,但我忘了分享,这里是:

JsonFactory jsonFactory = new JacksonFactory();
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
httpRequest.setReadTimeout(60000); // 60 seconds
}
};

BatchRequest batch = p.batch(httpRequestInitializer);
Pagespeedonline p = new Pagespeedonline.Builder(transport, jsonFactory, httpRequestInitializer).setApplicationName(APP_NAME).build();

//Loop to add as many as you want
for (int i = 0; i < urls.size(); ++i) {
Pagespeedonline.Pagespeedapi.Runpagespeed check = p.pagespeedapi().runpagespeed(urls.get(i)).setKey(GOOGLE_KEY).setStrategy(DEVICE);
check.queue(batch, callback);
}

batch.execute();

这是回调:

JsonBatchCallback<PagespeedApiPagespeedResponseV5> callback = new JsonBatchCallback<PagespeedApiPagespeedResponseV5>() {

public void onSuccess(PagespeedApiPagespeedResponseV5 response, HttpHeaders responseHeaders) {
//ON SUCCESS
}
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
//ON FAILURE
}
};

关于java - PageSpeed API - Java 中的批处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56647794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com