[英]Play 2.6: get response body in custom http action
A while ago, I asked how to get the body from a Result in Play 2.5.0 Java. 前一段时间,我问如何从Play 2.5.0 Java的Result中获取主体。
The answer was basically to use play.core.j.JavaResultExtractor
. 答案基本上是使用play.core.j.JavaResultExtractor
。 I am now upgrading to 2.6, and JavaResultExtractor
no longer exists (or at least is not public). 我现在升级到2.6,并且JavaResultExtractor
不再存在(或至少不是公共的)。
How does one do this in Play 2.6? 如何在Play 2.6中做到这一点?
I did find Result.body().consumeData
which seems like it might work, but also comes with the worrisome warning: 我确实找到了Result.body().consumeData
,它似乎可以正常工作,但同时也带来了令人担忧的警告:
This method should be used carefully, since if the source represents an ephemeral stream, then the entity may not be usable after this method is invoked. 应谨慎使用此方法,因为如果源表示短暂的流,则在调用此方法后该实体可能不可用。
I suppose that, since I am doing this in an action, I could call consumeData to get all of the data into a local variable, process that and then return a new result with the stored data. 我想,由于我是在一个操作中执行此操作的,因此可以调用consumpData将所有数据放入局部变量中,进行处理,然后使用存储的数据返回新结果。 That only fails in the case where the data is too big to fit into memory, which is not something I am currently expecting. 这仅在数据太大而无法放入内存的情况下才失败,这不是我目前所期望的。
In in Play 2.6 it is still possible to re-implement 2.5 functionality. 在Play 2.6中,仍然可以重新实现2.5功能。 Please have a look at the example that get Json body from Result: 请看一下从Result获取Json正文的示例:
public static JsonNode resultToJsonNode(final Result result, final long timeout, final Materializer mat)
throws Exception {
FiniteDuration finiteDuration = Duration.create(timeout, TimeUnit.MILLISECONDS);
byte[] body = Await.result(
FutureConverters.toScala(result.body().consumeData(mat)), finiteDuration).toArray();
ObjectMapper om = new ObjectMapper();
final ObjectReader reader = om.reader();
return reader.readTree(new ByteArrayInputStream(body));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.