播放 2.6:在自定义 http 操作中获取响应正文

Play 2.6: get response body in custom http action

前段时间问过

答案基本上是使用play.core.j.JavaResultExtractor。我现在升级到 2.6,并且 JavaResultExtractor 不再存在(或者至少不存在 public)。

如何在 Play 2.6 中做到这一点?

我确实找到了 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.

我想,因为我是在一个动作中执行此操作,所以我可以调用 consumeData 将所有数据放入一个局部变量中,对其进行处理,然后 return 使用存储的数据生成一个新结果。只有在数据太大无法放入内存的情况下才会失败,这不是我目前所期望的。

在 Play 2.6 中,仍然可以使用 re-implement 2.5 功能。请查看从结果中获取 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));
}