0

[Java DSL] I'm trying to post a stream of bytes to a server (as the body) using the client api in real-time but won't know the length prior to the start of the request.

I can't figure out how to do this from the akka-http documentation, has anyone attempted this?

Oakdale
  • 138
  • 1
  • 7

1 Answers1

0

Given that, you have created a materializer from the Akka context and have a Source that generates ByteString objects called mysource:

Http httpContext = 
    Http.get(context().system());

Source<ByteString, NotUsed> chunked = 
    mysource.map(str -> ByteString(str.concat("\n")))
        .concat(Source.single(ByteString.empty()));

HttpRequest post = HttpRequest.POST("http://some-server/address")
    .withEntity(HttpEntities.createChunked(ContentTypes.APPLICATION_OCTET_STREAM, chunked))
    .withProtocol(HttpProtoclas.HTTP_1_1);

CompletionStage<HttpResponse> result =
    httpContext.singleRequest(post, materializer);

Note that we concatenate an empty ByteString Source object to the original Source in order to signal the end of the chunked stream.

If you are issuing this from within an actor it's best to use a pipe() to submit the final request.

Oakdale
  • 138
  • 1
  • 7