0

I am facing trouble of extracting the response body as a string value from a http response in Java. I did an attempt with the answers here: akka HttpResponse read body as String scala however I could not find something which would work out. By trail-and-error I came up to the following snippet, however I don't think it should be this difficult. So I am seeking for a simple way to do this. The current code snippet which I am using is:

import akka.actor.ActorSystem;
import akka.http.javadsl.Http;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.stream.javadsl.Sink;
import akka.util.ByteString;
import com.typesafe.config.ConfigFactory;

public class App {

    public static void main(String[] args) {
        ActorSystem actorSystem = ActorSystem.create(ClientConfig.class.getSimpleName(), ConfigFactory.defaultApplication(App.class.getClassLoader()));
        Http httpClient = akka.http.javadsl.Http.get(actorSystem);
        HttpRequest httpRequest = HttpRequest.create("https://stackoverflow.com");

        String responseBody = httpClient.singleRequest(httpRequest)
                .thenApply((HttpResponse httpResponse) ->
                        httpResponse.entity()
                                .getDataBytes()
                                .fold(ByteString.emptyByteString(), ByteString::concat)
                                .map(ByteString::utf8String)
                                .runWith(Sink.head(), actorSystem)
                                .toCompletableFuture()
                                .join())
                .toCompletableFuture()
                .join();

        System.out.println(responseBody);
    }

}

I am just wondering whether the body of the thenApply to transform the entity to a string needs to be this complex or are there other ways within the Akka library itself to simplify it.

Hakan54
  • 3,121
  • 1
  • 23
  • 37

1 Answers1

0

Simple HttpRequest in Scala 3 to get the html string as response:

object HttpTest {

  given system: ActorSystem[_] = ActorSystem(Behaviors.empty, "SingleRequest")
  // needed for the future flatMap/onComplete in the end
  given executionContext: ExecutionContext = system.executionContext
  

  @main def httpExample() = {
    val result = Http().singleRequest(HttpRequest(uri = "https://stackoverflow.com", method = HttpMethods.GET))

    val str = result.map(e => {
        Unmarshal(e.entity).to[String]
      }).flatten

    println(Await.result(str, 10.seconds))
  }
}
Emiliano Martinez
  • 4,073
  • 2
  • 9
  • 19