Akka http using java - get string from RequestEntity

I am trying to get the body of an HTTP request, but it seems that it is not as simple as it might sound, unless, of course, I am missing something.

I have an instance HttpRequest(from akka.http.javadsl.model) and I can get from it RequestEntity, but I cannot figure out how to extract a string from an object.
I want to do this synchronously, just a simple operation of getting a string from there.

I tried two different ways:

(1)

Source<ByteString, Object> source = RequestEntity.getDataBytes();

I'm not sure what I should do with source, it has many methods, and it is not clear how to use them, and if any of them can really help me.

(2)

Unmarshaller<HttpEntity, String> unmarshaller = Unmarshaller.entityToString();
CompletionStage<String> result = unmarshaller.unmarshall(entity, ExecutionContext, Materializer);

unmarshaller.unmarshall RequestEntity, ExecutionContext a Materializer, , CompletionStage<String>, , .

java , , , , Unmarshalling:

Unmarshaller.entityToString, Unmarshaller.entityToByteString, Unmarshaller.entityToByteArray, Unmarshaller.entityToCharArray

, .

?

+4
2

ExecutionContext Materializer, akka-http. Future, HTTP , Unmarshaller:

    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("http://stackoverflow.com/"), materializer).
        thenCompose(response -> Unmarshaller.entityToString().unmarshal(response.entity(), ExecutionContexts.global(), materializer)).
        thenAccept(System.out::println);
+2

Java , , .

, entity , :

path("example", () ->
  entity(Unmarshaller.entityToString(), (string) -> {
    System.out.println("request body: " + string);
    return complete("ok");
  })
)

, JVM, . 8M , withSizeLimit withoutSizeLimit.

Akka 21001, .

0

Source: https://habr.com/ru/post/1648293/


All Articles