我试图将REST服务中的json响应解组为Java pojo,但我无法这样做。
HttpResponse
中的响应正文作为字符串? 我已尝试查看Akka文档和其他网站,但无法在任何地方找到答案。
final Http http = Http.get(actorSystem);
CompletionStage<HttpResponse> response =
http.singleRequest(HttpRequest.GET("http://127.0.0.1:8081/orders/24"));
HttpResponse httpResponse = response.toCompletableFuture().get();
Order s =
Jackson.unmarshaller(Order.class)
.unmarshal(
httpResponse.entity(),
ExecutionContexts.global(),
ActorMaterializer.create(actorSystem)
).toCompletableFuture()
.get();
System.out.println("response body: " + s); `
答案 0 :(得分:0)
如何将HttpResponse中的响应主体作为字符串获取?
以阻止方式(不推荐,但要从代码段继续):
HttpResponse httpResponse = response.toCompletableFuture().get();
Strict strict = httpResponse.entity().toStrict(TIMOUT_MS, mat).toCompletableFuture().get();
String body = strict.getData().utf8String();
更好的非阻塞方式是异步执行:
response.thenCompose(response ->
response.entity().toStrict(TIMEOUT, mat)
).thenApply(entity ->
entity.getData().utf8String())
).thenApply(body ->
// body is a String, do some logic on it here...
);
如果你还没有一个(这个类型来自akka-stream库,那么你需要依赖它),可以像这样创建一个materializer(mat):
Materializer mat = ActorMaterializer.create(actorSystem);
如何将响应主体直接解组为Java pojo?
尚未对此进行测试,但应根据docs
进行操作Unmarshaller<HttpEntity, Order> unmarshaller = Jackson.unmarshaller(Order.class);
response.thenCompose(response ->
response.entity().toStrict(TIMEOUT, mat)
).thenApply(entity ->
unmarshaller.unmarshal(entity, mat)
)
以下代码中的GET请求是否异步?
是的。除非您阻止返回的CompletionStage,否则就像使用response.toCompletableFuture()。get()。