编程语言
首页 > 编程语言> > 使用java的Akka http – 从RequestEntity获取String

使用java的Akka http – 从RequestEntity获取String

作者:互联网

我正试图获取一个http请求的主体,但它似乎并不像它听起来那么简单,除非我当然缺少一些东西.

我有一个HttpRequest的实例(来自akka.http.javadsl.model),我可以得到RequestEntity,但我无法弄清楚如何从实体中提取字符串.
我想同步这样做,只是一个简单的操作,让字符串从那里.

我尝试了两种不同的途径:

(1)

Source<ByteString, Object> source = RequestEntity.getDataBytes();

我不确定我应该对源做什么,它有很多方法,而且还不清楚如何使用它们,如果它们中的任何一个可以真正帮助我.

(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.您将需要编写使用Unmarshaller提供的HTTP请求的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("https://stackoverflow.com/"), materializer).
        thenCompose(response -> Unmarshaller.entityToString().unmarshal(response.entity(), ExecutionContexts.global(), materializer)).
        thenAccept(System.out::println);

标签:java,asynchronous,akka,unmarshalling,akka-http
来源: https://codeday.me/bug/20190702/1353544.html