【问题标题】:Akka-http create Chunked entity in Java (convert from Scala)Akka-http 在 Java 中创建 Chunked 实体(从 Scala 转换)
【发布时间】:2017-03-03 18:41:47
【问题描述】:

我正在尝试将以下代码从 Scala 转换为 Java:

    object ChunkedStaticResponse {
        private def createStaticSource(fileName : String) = 
          FileIO
            .fromPath(Paths get fileName)
            .map(p => ChunkStreamPart.apply(p))


        private def createChunkedSource(fileName : String) =
          Chunked(ContentTypes.`text/html(UTF-8)`, createStaticSource(fileName))

        def staticResponse(page:String) =
        HttpResponse(status = StatusCodes.NotFound,
          entity = createChunkedSource(page))
    }

但是我在执行第二种方法时遇到了麻烦。到目前为止,我已经做到了这一点:

class ChunkedStaticResponseJ {

  private Source<HttpEntity.ChunkStreamPart, CompletionStage<IOResult>> 
     createStaticSource(String fileName) {
     return  FileIO
            .fromPath(Paths.get(fileName))
            .map(p -> HttpEntity.ChunkStreamPart.create(p));
  }

  private HttpEntity.Chunked createChunkedSource(String fileName) {
    return HttpEntities.create(ContentTypes.TEXT_HTML_UTF8, 
           createStaticSource(fileName)); // not working
  }

  public HttpResponse staticResponse(String page)  {
    HttpResponse resp =  HttpResponse.create();
    return resp.withStatus(StatusCodes.NOT_FOUND).withEntity(createChunkedSource(page));
  }
}

我不知道如何在第二种方法中创建分块源。 有人可以建议一种方法吗?另外,我通常是在正确的道路上吗?

【问题讨论】:

    标签: akka akka-http


    【解决方案1】:

    如果您只想从文件中读取的每个 ByteString 元素中创建一个 Chunk,您可以利用 Chunked.fromData(JavaDSL 中的 HttpEntities.createChunked)。

    这是 Scala 端的结果

      object ChunkedStaticResponse {
        private def createChunkedSource(fileName : String) =
          Chunked.fromData(ContentTypes.`text/html(UTF-8)`, FileIO.fromPath(Paths get fileName))
    
        def staticResponse(page:String) =
          HttpResponse(status = StatusCodes.NotFound,
            entity = createChunkedSource(page))
      }
    

    这将是它的 JavaDSL 对应物

    class ChunkedStaticResponseJ {
        private HttpEntity.Chunked createChunkedSource(String fileName) {
            return HttpEntities.createChunked(ContentTypes.TEXT_HTML_UTF8, FileIO.fromPath(Paths.get(fileName)));
        }
    
        public HttpResponse staticResponse(String page)  {
            HttpResponse resp =  HttpResponse.create();
            return resp.withStatus(StatusCodes.NOT_FOUND).withEntity(createChunkedSource(page));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 2018-06-04
      相关资源
      最近更新 更多