我正在尝试获取 http 请求的正文,但它似乎并不像听起来那么简单,当然除非我遗漏了什么。
我有一个 HttpRequest
的实例(来自 akka.http.javadsl.model
),从中我可以获得 RequestEntity
,但我不知道如何从实体中提取字符串。
我想同步执行此操作,只需一个简单的操作即可从那里获取字符串。
我尝试了两种不同的路径:
(1)
Source<ByteString, Object> source = RequestEntity.getDataBytes();
我不确定我应该用 source
做什么,它有很多方法,目前还不清楚如何使用这些方法以及它们是否真的可以帮助我。
(2)
Unmarshaller<HttpEntity, String> unmarshaller = Unmarshaller.entityToString();
CompletionStage<String> result = unmarshaller.unmarshall(entity, ExecutionContext, Materializer);
调用 unmarshaller.unmarshall
不仅需要 RequestEntity
的实例还有一个ExecutionContext
和一个 Materializer
我在解码部分没有,它也返回 CompletionStage<String>
这是完全多余的,因为我希望它同步完成。
java 的文档和示例没有多大帮助,因为它们非常简短,如果它们存在的话,例如在 Marshalling & Unmarshalling section 中。 :
Use the predefined Unmarshaller.entityToString, Unmarshaller.entityToByteString, Unmarshaller.entityToByteArray, Unmarshaller.entityToCharArray to convert to those basic types
如您所见,这不是很有用。
有什么想法吗?
最佳答案
您可以使用全局 ExecutionContext
和用于运行 akka-http
的相同 Materializer
。您需要将发出 HTTP 请求的 Future
与 Unmarshaller
提供的Future
组合起来:
import akka.actor.ActorSystem;
import akka.dispatch.ExecutionContexts;
import akka.http.javadsl.Http;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.ResponseEntity;
import akka.http.javadsl.unmarshalling.Unmarshaller;
import akka.stream.ActorMaterializer;
import akka.stream.Materializer;
ActorSystem system = ActorSystem.create();
Materializer materializer = ActorMaterializer.create(system);
Http.get(system).
singleRequest(HttpRequest.create("http://stackoverflow.com/"), materializer).
thenCompose(response -> Unmarshaller.entityToString().unmarshal(response.entity(), ExecutionContexts.global(), materializer)).
thenAccept(System.out::println);
关于java - Akka http 使用 java - 从 RequestEntity 获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38445376/