gpt4 book ai didi

java - 使嵌套的http请求java异步

转载 作者:行者123 更新时间:2023-11-30 08:34:12 26 4
gpt4 key购买 nike

我正在为我的项目使用 play java(java play ws API) 和

private CompletionStage<String> getAuthToken() {
WSRequest request = ws.url(URL);
WSRequest complexRequest = request.setHeader("X-API-Key", X_API_KEY)
.setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE)
.setHeader(AUTHORIZATION, CLIENT_DETAILS_BASE64_ENCODE);
CompletionStage<WSResponse> responsePromise = complexRequest.post(GRANT_TYPE + "="
+ PASSWORD + "&" + USERNAME + "=" + USERNAME + "&" + PASSWORD + "=" + PASSWORD);
return responsePromise.thenApply(response-> getAuthToken2().toString());
}

private CompletionStage<String> getAuthToken2() {
WSRequest request = ws.url(URL);
WSRequest complexRequest = request.setHeader("X-API-Key", X_API_KEY)
.setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE)
.setHeader(AUTHORIZATION, CLIENT_DETAILS_BASE64_ENCODE);
CompletionStage<WSResponse> responsePromise = complexRequest.post(GRANT_TYPE + "="
+ PASSWORD + "&" + USERNAME + "=" + USERNAME + "&" + PASSWORD + "=" + PASSWORD);
return responsePromise.thenApply(response-> addIdentity(response.asJson().findValue("access_token").toString()).toString());
}

我犯了什么错误?如何一个接一个地发出嵌套请求?

我明白了

java.util.concurrent.CompletableFuture@75c6e852[Not completed]

作为对我客户的回应

最佳答案

您必须使用 thenCompose 来链接多个 http 请求。这是一个工作示例:对于三个站点,我们将获取它们的页面并将状态代码添加到 JSON 对象。最后,我们返回该对象。

public CompletionStage<Result> getSites() {
ObjectNode hosts = Json.newObject();
return ws.url("https://www.facebook.com").get()
.thenCompose(res -> {
hosts.put("facebook", res.getStatus());
return ws.url("https://www.google.com").get();
})
.thenCompose(res -> {
hosts.put("google", res.getStatus());
return ws.url("https://www.twitter.com").get();
})
.thenApply(res -> {
hosts.put("twitter", res.getStatus());
return ok(hosts);
});
}

关于java - 使嵌套的http请求java异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38980056/

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