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.