Skip to content

Instantly share code, notes, and snippets.

@hakuch
Last active March 1, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hakuch/1cd0bdc051bf9d7e8e41 to your computer and use it in GitHub Desktop.
Save hakuch/1cd0bdc051bf9d7e8e41 to your computer and use it in GitHub Desktop.
import akka.http.scaladsl.model._
import akka.stream._
import scala.concurrent.duration._
import scala.concurrent._
object Http {
def responseBodyAsString(r: HttpResponse)(implicit m: Materializer): String =
Await.result(
r.entity.dataBytes.runWith(Sink.head).map(_.utf8String),
Duration.Inf)
}
@ktoso
Copy link

ktoso commented Sep 29, 2015

Almost, I answered in more detail on gitter: ☝️ September 29, 2015 7:56 PM

A quick one is:

r.entity.toStrict(200.millis).dataBytes.runWith(Sink.head).map(_.utf8String)

In general we encourage staying in streaming land.
I made a ticket for improving docs to explain this exact use case akka/akka#18599

@phani1kumar
Copy link

toStrict doesn't seem to have the dataBytes method. I am getting compilation error there. Please suggest if I am doing anything wrong.

def responseBodyAsString(r: HttpResponse)(implicit m: Materializer): String =
    Await.result(
      r.entity.toStrict(200.millis).dataBytes.runWith(Sink.head).map(_.utf8String),Duration.Inf)

@okapies
Copy link

okapies commented Dec 2, 2017

The following works for me.

r.entity.toStrict(200.millis).map(_.data.utf8String)

@pete-proton
Copy link

@ktoso could you have a look at the query below. have the same question. thanks in advance.

toStrict doesn't seem to have the dataBytes method. I am getting compilation error there. Please suggest if I am doing anything wrong.

def responseBodyAsString(r: HttpResponse)(implicit m: Materializer): String =
    Await.result(
      r.entity.toStrict(200.millis).dataBytes.runWith(Sink.head).map(_.utf8String),Duration.Inf)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment