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

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

我有一个HttpRequest的实例(来自akka.http.javadsl.model),我可以得到RequestEntity,但我无法弄清楚如何从实体中提取字符串.

我想同步这样做,只是一个简单的操作,让字符串从那里.

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

(1)

Source source = RequestEntity.getDataBytes();

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

(2)

Unmarshaller unmarshaller = Unmarshaller.entityToString();

CompletionStage 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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值